简体   繁体   English

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

[英]How to pass a variable in index.html to a service?

Hey guys complete noob to angular. 嘿,伙计们完成了菜鸟的准备。 Can you help me? 你能帮助我吗? So I have the following code provided by google oauth: 所以我有谷歌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>

This is index.html 这是index.html

I want to be able to access the given token from a factory that I have in angular. 我希望能够从有角的工厂访问给定令牌。 Is this through $scope? 这是通过$ scope吗?

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

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


return service


}]);

Thanks 谢谢

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

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

You can address this method through callback or just onSignIn()//it returns id_token after my changes 您可以通过回调或仅通过onSignIn()//it returns id_token解决此方法, onSignIn()//it returns id_token在我更改后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;
}

in your service: 为您服务:

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
                }
            }]);

in controller: 在控制器中:

Service.sendRequest();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM