简体   繁体   中英

Angular JS Promise only resolving in markup, not model

I'm having an issue resolving my promise—the strange this is that in my markup:

{{details.customer_email}}

It resolves properly , and displays the e-mail address returned by the '$http` request.

However, attempting to access this:

$scope.user = {
    ...
    emailAddress : $scope.details.customer_email,
    ...
};

is null .

Here's the relevant block:

$scope.session = {
    is_authenticated: false,
    customer_email: null
};

var detailsDeferred = $q.defer();

$scope.details = detailsDeferred.promise;

$scope.authed = function () {

    $http({
        url: 'http://api.foo/auth',
        withCredentials: true,
        method: "GET",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).success(function (data, status, xhr) {

            $scope.session = {
                is_authenticated: data.is_authenticated,
                customer_email: data.customer_email
            };

            detailsDeferred.resolve($scope.session);


        })
        ...

    return $scope.session;

};

$scope.authed();

$scope.user = {
    ...
    emailAddress: $scope.session.customer_email
        ...
    };

It's working in your markup is because angular's template engine is "promise aware", it's very convenient.

Quoted from the doc :

$q promises are recognized by the templating engine in angular, which means that in templates you can treat promises attached to a scope as if they were the resulting values.

In your JavaScript code, however, you have to handle it all by yourself:

$scope.user = {
    ...
    emailAddress : null,
    ...
};

$scope.details.then(function(details) {
    $scope.user.emailAddress = details.customer_email;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM