将变量从工厂分配给控件不起作用 [英] Assigning variable from a factory to a control doesn't work

查看:69
本文介绍了将变量从工厂分配给控件不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的html是这样的:

My html is this:

<body ng-controller="MainCtrl as ctrl" class="bodyContainer">
<div ng-repeat="stuff in ctrl.stuffies">
    here
</div>

这是我的控制者:

angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        BaseService.fetch.stuffs(function() {
            self.stuffies = BaseService.stuffies;
            console.log(self.stuffies);
            self.cerrorMessages = BaseService.cerrorMessages;
        });
    }]);

这是我的BaseApp:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;


        /* All functions which call fetch should have a callback function
         * on the front-end which sets 
         * 1) a variable (i.e. stuffies etc.)
         * 2) and BaseService.cerrorMessages. */
        self.fetch = {
             stuff: function(callback) {
                 $http.get("/stuffs/")
                 .then(function(response) {
                     self.stuffies = response.data;
                     callback();
                 }, function(response) {
                     self.accessErrors(response.data);
                     callback();
                 });
             }
        };

问题是,即使它在self.stuffies中记录了一个项目(运行此行:console.log(self.stuffies);时),也没有在HTML中打印here. ctrl.stuffies内部似乎没有任何东西.我尝试将console.log(self.stuffies);移到BaseService.fetch.stuffs(function()之外,并且它记录了undefined.如何使ctrl.stuffies成为BaseService.stuffies?

The problem is, even though it logs an item inside self.stuffies (when this line is run: console.log(self.stuffies);), here is not printed in the HTML. There doesn't seem to be anything inside ctrl.stuffies. I tried moving console.log(self.stuffies); outside of BaseService.fetch.stuffs(function() and it logs undefined. How do I get ctrl.stuffies to be BaseService.stuffies?

推荐答案

$ http服务无需使用回调,因为它会返回promise:

There is no need to use callbacks with the $http service as it returns promises:

//.factory("BaseService", ["$http", "$window", function($http, $window) {
app.service("BaseService", ["$http", "$window", function($http, $window) {
    //var self = this;


    /* All functions which call fetch should have a callback function
     * on the front-end which sets 
     * 1) a variable (i.e. stuffies etc.)
     * 2) and BaseService.cerrorMessages. */
    this.fetch = {
         stuff: function() {
           //vvvv RETURN the promise
           return $http.get("/stuffs/")
             .then(function(response) {
                 //vvvv RETURN the data
                 return response.data;
                 //self.stuffies = response.data;
                 //callback();
           });//, function(response) {
             //    self.accessErrors(response.data);
             //    callback();
             //});
         }
    };
});

在服务中无需执行任何带有$ http错误的操作.错误将在承诺中自动结转.

There is no need to do anything with $http errors in the service. Errors will be carried forward automatically in the promise.

然后在控制器中从诺言中提取数据(或错误):

Then in the controller extract the data (or the error) from the promise:

/* REPLACE
BaseService.fetch.stuffs(function() {
    self.stuffies = BaseService.stuffies;
    console.log(self.stuffies);
    self.cerrorMessages = BaseService.cerrorMessages;
});
*/


BaseService.fetch.stuffs
  .then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});

有关更多信息,请参见

MDN JavaScript参考-声明

我将您的服务更改为工厂,并做到了这一点: 并以这种方式使用了它:

BaseService.fetch.stuffs() 
  .then(function(data) {
    self.stuffs = data;
    console.log(self.stuffs);  
}).catch(function(errorResponse) { 
    self.cerrorMessages = errorResponse.data; 
});

这样可以吗(使用工厂,因为工厂内部还有其他功能,我不想将它们全部更改为服务)?

Is this fine (using factory because there are other functions inside the factory as well and I don't want to have to change them all to services)?

抱歉,工厂是

self.fetch = { 
    stuffs: function() { 
        return $http.get("/stuffs/")
          .then(function(response) {
              return response.data; 
        });
    }
};

服务或工厂都可以工作.通过服务,可以通过将属性添加到自动返回的this上下文中来添加功能(除非被return语句覆盖).对于工厂,必须强制使用return语句.函数被添加到返回的对象中.选择是风格的问题.它们都以相同的方式使用.

Either a service or a factory will work. With a service, functions can be added by adding properties to the this context which is automatically returned (unless overridden with a return statement). With a factory, a return statement is manditory. Functions are added to the object returned. The choice is a question of style. They are both used the same way.

这篇关于将变量从工厂分配给控件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆