在一个控制器中更新服务变量,并在另一个控制器 - Angular JS中使用更新的值

Updating a service variable in one controller and using the updated value in another controller - Angular JS

本文关键字:更新 控制器 Angular JS 另一个 变量 一个 服务      更新时间:2023-09-26

我在controller.js中定义了一个名为NameService的服务。我想在两个不同的控制器中使用NameService中存在的变量。

我的服务如下

App.service('NameService', function(){
  this.Name = "";
  this.getName = function(){
    return this.Name;
  };
  this.setName = function(name){
    this.Name = name;
  }
});

我有一个名为 netController 的控制器,我正在其中更新Nameservice中存在的 Name 变量的值。我想在我的page1Controller中使用更新的值。

NetController如下:

App.controller('netController', ['$scope','$http','$window','NameService',  function($scope,$http,$window,NameService)
    {
        $scope.initNet = function()
        {
            $http.post('/initNet',$scope.network).success(function(response) 
            {
                if(response.status == "true")
                {
                     $scope.$watch('NameService.setName()', function(){
                        NameService.Name = $scope.network.name;
                     });
                     NameService.setName($scope.network.name);
                     $window.location.href = '/page1';
                } 
                else
                {
                    $scope.error = "Error!";
                }
            });
        }
    }]);

如果我在我的netControllerconsole.log(NameService.netName);,它正在打印更新的值。

page1Controller如下

    App.controller('page1Controller', ['$scope', '$http','NameService', function($scope, $http,NameService)
    {
          console.log(NameService.Name);
    }]);

什么时候在我的page1Controller中做console.log(NameService.name);它给出空字符串。

有人可以帮我解决这个问题吗?

使用工厂而不是服务

gisApp.factory('NameService', function () {
    var _name = "";
    return {
        getName: function () {
            return _name;
        },
        setName: function (name) {
            _name = name;
        }
    }
});

因为当您调用以打印该变量时,它尚未定义。$http回报承诺,它需要一些时间间隔。您是否尝试过在page1Controller中设置间隔?喜欢

App.controller('page1Controller', ['$scope', '$http','NameService', '$timeout' function($scope, $http,NameService, $timeout)
{
    $timeout(function(){
      console.log(NameService.name)
    },2000);
...

编辑

然后尝试这样的事情

gisApp.service('NameService', function(){
  return {
   Name: '',
   getName: function(){
     return this.Name;
   },
   setName: function(name){
     this.Name = name;
   }
});

由于您使用的语法,您必须使用"new"创建该服务的实例才能将其用作类。