CiscoKidx
CiscoKidx

Reputation: 920

AngularJS: .value persistance

Consider the following:

AngularJS:

angular.module('app', [])

.value('userData', {})

.factory('AuthService', function (userData) {

    $http.put('/login', {
    ...
    })

    .then(function onSuccess(res) {
        userData = res.data.user
    })

})

.controller('Dashboard', function (userData) {
    $scope.user = userData
})

HTML:

<div ng-controller="Dashboard"> {{ user.name }} </div>

Should userData be populated when it is time for {{ user.name }} ? Should userData persist through a refresh? If the goal is to display information received from the API specific to the user, What other options do I have besides storing res.data.user to local storage?

Upvotes: 2

Views: 31

Answers (1)

Phil
Phil

Reputation: 164890

Direct assignments like

userData = res.data.user;

break JS references, meaning anything that referenced the variable won't get the new value.

A better option in my opinion is to save a reference to the promise in your factory

.factory('AuthService', function ($http) {
    return $http.put('/login', {
        ...
    }).then(function (res) {
        return res.data.user;
    });
})

The HTTP request will only run once when your factory is created but the promise will be saved against the factory name. Then your controller (or anything else) can simply use

$scope.user = 'Loading...'; // if you want to show something right away
AuthService.then(function(userData) {
    $scope.user = userData;
});

Upvotes: 2

Related Questions