将返回的auth2的值注入到angular变量中

Inject value of returned auth2 to angular variable

本文关键字:angular 变量 返回 auth2 注入      更新时间:2023-09-26

我已经找了一段时间,没有找到解决我的问题的方法,尽管我认为这可能很简单。

我使用angularJS和认证与谷歌auth2,以检索当前登录的用户。我想把用户名添加到一个angularJS变量中,只是为了在页面上显示它(至少现在是这样)。

这是我的相关html:

<meta name="google-signin-client_id" content="(((cut out my client id here))">
<script src="bower_components/angular/angular.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<body ng-app="CalendarApp" >
  <div class="container" ng-controller="CalendarCtrl">
    <div class="header well" >
      <h1> Some heading </h1>
      <p id="welcometext"> Welcome, {{userName}} </p>
    </div>
  </div>
</body>

和这里的相关js:

var myApp = angular.module('CalendarApp', []);
myApp.controller('CalendarCtrl', ['$scope', function($scope) {
$scope.userName = "tst";
gapi.load('auth2', function() {
  auth2 = gapi.auth2.init({
    fetch_basic_profile: true,
    scope: 'profile'
  });
  // Sign the user in, and then retrieve their ID.
  auth2.signIn().then(function() {
    var profile = auth2.currentUser.get().getBasicProfile();
    $("#welcometext").text("Welcome, " + profile.getName()); //this is my current workaround, but don't like it.
    $scope.userName = profile.getName();
    console.log($scope.userName); //this prints the correct name
  });
}); // gapi.load

正如您可以从我的注释中得出的那样,auth调用工作并检索数据。我想从角度$scope.userName来访问它。但是如果我在站点上显示它,它只显示" test ",而忽略$scope.userName = profile.getName();语句。

我很确定这可能只是我的一个愚蠢的错误,但我已经在这上面花了很多时间了。

感谢任何帮助,谢谢!

要将auth2.signIn()承诺转换为与AngularJS摘要循环集成的$q服务承诺,请使用$q.when:

gapi.load('auth2', function() {
  auth2 = gapi.auth2.init({
    fetch_basic_profile: true,
    scope: 'profile'
  });
  // Sign the user in, and then retrieve their ID.
  //auth2.signIn().then(function() {
  //USE $q.when to integrate with AngularJS digest cycle
  $q.when(auth2.signIn()).then(function() {
    var profile = auth2.currentUser.get().getBasicProfile();
    //$("#welcometext").text("Welcome, " + profile.getName()); //this is my current workaround, but don't like it.
    $scope.userName = profile.getName();
    console.log($scope.userName); //this prints the correct name
  });
}); // gapi.load

通过将gapi承诺转换为$q服务承诺,AngularJS框架将通过.then方法对$scope的变化做出反应。

From the Docs:

当美元

将一个对象包装成一个$q promise,该对象可能是一个值或一个(第三方)可执行的promise。当你处理的对象可能是承诺,也可能不是承诺,或者承诺来自一个不可信的来源时,这是很有用的。

——AngularJS $q Service API参考- $q.when

你不需要这样做:

$("#welcometext").text("Welcome, " + profile.getName()); //this is my current workaround, but don't like 

你所需要做的就是:

$scope.userName = profile.getName();

如果删除jQuery仍然不起作用,

写这个:

$scope.userName = profile.getName();
$timeout(function() {
   $scope.$apply();
});

巴拉特。