1

I have a problem using global variables in angularjs I have seen this question Global variables in AngularJS and the answer worked fine but I want to return in my service something like this

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

The console is printing the value as "true" which is what I need. But in my controller, I am trying to print the value and it prints undefined

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

Can someone help me please !!!

TonySader
  • 47
  • 5

2 Answers2

1

First of all, if your post request is asynchronous, please consider using asynchronous to read, and if the read value only needs to be read once, you can refer to my way below.

Here's my definition. I hope it will be helpful to you.

1.Definition:

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.Use demonstration:

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

Can you give this a try and see if you get the results?

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>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70