全局变量作为angularjs中的服务

时间:2018-12-15 00:51:48

标签: angularjs global-variables angularjs-service

我在angularjs中使用全局变量时遇到问题 我看过这个问题 Global variables in AngularJS 和答案很好 但是我想像这样返回我的服务

bookModule.factory('UserService', function (viewModelHelper) {
    function get() {
        var rt;
        viewModelHelper.apiPost('Language/getLanguageIsArabic', null,
            function (result) {
                rt = result.data;
                console.log(rt);
                return rt;
            });
        }
    return {
        name: get()
    };
});

控制台将值打印为“ true”,这是我需要的。 但是在我的控制器中,我试图打印该值,并且打印出未定义的值

bookModule.controller("bookHomeController",
function ($scope,  bookService, UserService, viewModelHelper, $filter) {
 $scope.arabic = UserService.name; 
 console.log($scope.arabic);     
}

有人可以帮我吗!!!

2 个答案:

答案 0 :(得分:1)

首先,如果您的发布请求是异步的,请考虑使用异步读取,并且如果读取的值仅需要读取一次,则可以参考下面的方式。

这是我的定义。希望对您有帮助。

1。定义:

bookModule.Service('UserService', function (viewModelHelper) {
    var name='';
    this.get = function() {
        var deferred = $q.defer();
        if(!name)
        {
            //Because requests are asynchronous, it is recommended to read them asynchronously.
            viewModelHelper.apiPost('Language/getLanguageIsArabic', null,
            function (result) {
                deferred.resolve(result.data);
                name = result.data;
            });
        }else{
            deferred.resolve(name);
        }

        return deferred.promise;
    }
});

2。使用演示:

UserService.then(function(data){
   console.log(data); 
})

答案 1 :(得分:0)

您可以尝试一下,看看是否得到结果吗?

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, UserService, viewModelHelper) {
    $scope.arabic = UserService.getter(viewModelHelper); 
    console.log($scope.arabic.name); 
});

app.service('UserService', function(){
    this.getter = function (viewModelHelper) {
        var rt;
        viewModelHelper.apiPost('Language/getLanguageIsArabic', null,
            function (result) {
                rt = result.data;
                console.log(rt);
                return {
                        name: rt
                    };
            });
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<div ng-app="myApp" ng-controller="myCtrl">
    <p>The return from this page is:</p>
    <h3 ng-if="arabic">{{arabic.name}}</h3>
</div>