如何将index.html中的变量传递给服务?

时间:2015-09-01 15:20:12

标签: javascript angularjs web-services angular-services

嘿,伙计们将角落完成noob。你能帮助我吗? 所以我有以下代码由google oauth提供:

<script>
  function onSignIn(googleUser) {
    // Useful data for your client-side scripts:
    var profile = googleUser.getBasicProfile();
    console.log("ID: " + profile.getId()); // Don't send this directly to your server!
    console.log("Name: " + profile.getName());
    console.log("Image URL: " + profile.getImageUrl());
    console.log("Email: " + profile.getEmail());

    // The ID token you need to pass to your backend:
    var id_token = googleUser.getAuthResponse().id_token;
    console.log("ID Token: " + id_token);
  };
</script>

这是index.html

我希望能够从我有角度的工厂访问给定的令牌。这是通过$ scope?

App.factory('ranService', ['$http', '$q', function ($http, $q) {

var service = {};
var randomUrl = "http://zzz;
var googleToken;


return service


}]);

谢谢

2 个答案:

答案 0 :(得分:0)

$scope.id_token = googleUser.getAuthResponse().id_token;

将其放入您的控制器并在您的html文件中使用ng-controller指令以使用{{id_token}}。

答案 1 :(得分:0)

您可以通过回调或仅在我的更改后onSignIn()//it returns id_token来解决此方法

var profile;
function onSignIn(googleUser, callback) {
    // Useful data for your client-side scripts:
    if (googleUser)
        profile = googleUser.getBasicProfile();
    console.log("ID: " + profile.getId()); // Don't send this directly to your server!
    console.log("Name: " + profile.getName());
    console.log("Image URL: " + profile.getImageUrl());
    console.log("Email: " + profile.getEmail());

    // The ID token you need to pass to your backend:
    var id_token = googleUser.getAuthResponse().id_token;
    console.log("ID Token: " + id_token);
    //if there isn't success callback this callback use there  
    if (callback)
        callback(id_token);
    return id_token;
}

在您的服务中:

angular.module('serviceModule')
        .service('Service', ['$q', '$http',
            function ($q, $http) {

                function sendRequest() {

                    onSignIn(null, function (id_token) {
                        //you use this
                    })
                    //or just
                    var idToken = onSignIn();//it can return without params 
                }

                return {
                    sendRequest: sendRequest
                }
            }]);
控制器中的

Service.sendRequest();