简体   繁体   English

模型未在Promise angularjs的.then方法中更新

[英]model not updating in .then method of promise angularjs

I'm really struggling with this because it should be very simple. 我真的为此感到挣扎,因为它应该非常简单。 I have a route with a controller defined called login. 我有一条带有定义为login的控制器的路由。 In my template I have the following data binding {{error}} which is defined in my controller after executing a method from a custom service, and resolving the returned promise. 在我的模板中,我具有以下数据绑定{{error}} ,该数据绑定是在自定义服务中执行方法并解析返回的Promise后在控制器中定义的。

Controller 控制者

app.controller("login", ['$scope','XMLMC', 'ManageSettings', function ($scope,api,ManageSettings) {
    $scope.error = 'test';
    $scope.login = function() {
        var params = {
            selfServiceInstance: "selfservice",
            customerId: $scope.username,
            password: $scope.password
    };
        var authenticated = api.request("session","selfServiceLogon",params).then(function(response) {
            ManageSettings.set("session",response, $scope);

            if(response.status === "ok") {
                window.location.href = 'portal';
            } else {
                $scope.error = response["ERROR"];
                console.log($scope.error);
            }
        });

    };
}]);

The console shows Customer not registered. 控制台显示“客户未注册”。 Showing that $scope.error has been updated appropriately, but the view never gets updated. 显示$ scope.error已适当更新,但视图从未更新。 My service is below, and please note that I am doing nothing "outside" of angular and so I should not have to $apply() anything manually. 我的服务在下面,请注意,我在angular的“外部”没有做任何事情,因此我不必手动进行$apply()

app.factory("XMLMC", ['$http', '$q', function ($http, $q) {
    function XMLMC($http, $q) {
        $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

        var that= this;

        this.prepareForPost = function(pkg) {
            return JSON.stringify(pkg);
        };

        this.request = function(service, request, params, host, newsession) {
            var def = $q.defer();
            var P = def.promise;

            if(request === "analystLogon") {
                newsession = true;
            }

            var call = {
                service: service,
                method: request,
                params: params
            };

            if(host) {
                call.host = host;
            } else {
                call.host = "localhost";
            }

            if(newsession) {
                call.newsession = "true";
            }

            var pkg = {
                contents: this.prepareForPost(call)
            };




            $http.post('php/XMLMC/api.php', jQuery.param(pkg)).success(function (response,status) {
                    that.consume(response, def);

                }).error(function (response,status) {
                    def.reject(response,status);
                });

            return P;


        };

        this.consume = function(response, defer) {
            console.log(response);
            var resp = response[0],
                digested = {},
                i;

            digested.status = resp["attrs"]["STATUS"];
            var params = resp["children"][0]["children"];
            for(i=0; i < params.length; i++) {
                var key = params[i]["name"];
                var val = params[i]["tagData"];
                digested[key] = val;
            }

            defer.resolve(digested);
            //return digested;
        };
    }

    return new XMLMC($http, $q);
}]);

I've created a plunk here with the code exactly as it is on my test server. 我在这里用代码完全按照测试服务器上的代码创建了一个插件。 The routes and etc aren't working for obvious reasons, but you can at least see the code and how it works together 由于明显的原因,路由等无法正常工作,但是您至少可以看到代码及其协同工作的方式

http://plnkr.co/edit/AodFJfCijsp2VWxWpbR8?p=preview http://plnkr.co/edit/AodFJfCijsp2VWxWpbR8?p=preview

And here is a further simplified plunk where everything has one scope and one controller and no routes. 这是一个进一步简化的小节,其中的所有内容都有一个作用域和一个控制器,没有路由。 For some reason, this works in the plunk but the $http method fails in my server 由于某种原因,这在插件中有效,但是$ http方法在我的服务器中失败

http://plnkr.co/edit/nU4drGtpwQwFoBYBfuw8?p=preview http://plnkr.co/edit/nU4drGtpwQwFoBYBfuw8?p=preview

EDIT 编辑

Even this fails to update 即使这无法更新

var authenticated = api.request("session","selfServiceLogon",params).then(function(response) {
            ManageSettings.set("session",response, $scope);

    $scope.error = "foo!";

            if(response.status === "ok") {
                window.location.href = 'portal';
            } 
        });

It appears that $scope.$apply is indeed needed. 看来确实需要$ scope。$ apply。 See AngularJS - why is $apply required to properly resolve a $q promise? 参见AngularJS-为什么需要应用$来正确解决$ q承诺?

To quote @pkozlowski.opensource: 引用 @ pkozlowski.opensource:

In AngularJS the results of promise resolution are propagated asynchronously, inside a $digest cycle. 在AngularJS中,承诺解析的结果在$ digest周期内异步传播。 So, callbacks registered with then() will only be called upon entering a $digest cycle. 因此,仅在进入$ digest循环后才调用在then()中注册的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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