如何在AngularJS中更新全局变量?

时间:2021-08-28 23:23:02

Some application state information need to be stored in an Angular service so as to be globally accessed.

某些应用程序状态信息需要存储在Angular服务中,以便进行全局访问。

app.value('identity', {});

Then in a controller of my first view after log in. I make a GET api call to collect application state info from the server side. In the success callback, transfer the data into my global variable (service).

然后在登录后的第一个视图的控制器中。我进行GET api调用以从服务器端收集应用程序状态信息。在成功回调中,将数据传输到我的全局变量(服务)。

function successCallback(data) {
    identity.username = data.username;
    identity.email = data.email;
}

I assumed the identity will hold the data throughout my application. But it is not the case! In my other views, I inject identity into the controller

我假设身份将在整个申请过程中保存数据。但事实并非如此!在我的其他视图中,我将身份注入控制器

app.controller('anotherController', ['identity', anotherController];
function anotherController(identity){
    // access identity here.
    $scope.username=identity.username;
}

The first time I came to that view. username is correctly displayed on the page. But after a refresh, it appears the identity is null again! What can we do to make the value really persistent?

我第一次看到这个观点。用户名正确显示在页面上。但刷新后,它的身份再次显示为null!我们可以做些什么来使价值真正持久?

1 个解决方案

#1


2  

You're pointing the var identity to a new object that angular doesn't know about so it can't take that new value to another controller. I'd assign the callback's response to a property on identity:

您将var标识指向一个角度不知道的新对象,因此它不能将该新值传递给另一个控制器。我将回调的响应分配给身份上的属性:

app.value('identity', { data: null });

...

...

funciton successCallback(data) {
  // here, not overwriting identity, but editing a property
  identity.data = data;
}

controller:

控制器:

app.controller('anotherController', ['identity', anotherController];
  function anotherController($scope, identity){

  // add the svc to the scope so you can access its properties later
  $scope.identity = identity;
}

html template:

HTML模板:

{{ identity.data | json }}

#1


2  

You're pointing the var identity to a new object that angular doesn't know about so it can't take that new value to another controller. I'd assign the callback's response to a property on identity:

您将var标识指向一个角度不知道的新对象,因此它不能将该新值传递给另一个控制器。我将回调的响应分配给身份上的属性:

app.value('identity', { data: null });

...

...

funciton successCallback(data) {
  // here, not overwriting identity, but editing a property
  identity.data = data;
}

controller:

控制器:

app.controller('anotherController', ['identity', anotherController];
  function anotherController($scope, identity){

  // add the svc to the scope so you can access its properties later
  $scope.identity = identity;
}

html template:

HTML模板:

{{ identity.data | json }}