将变量从工厂分配给控件不起作用

Assigning variable from a factory to a control doesn't work

我的html是这样的:

<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);),here 也没有打印在 HTML。 ctrl.stuffies里面好像什么都没有。我尝试将 console.log(self.stuffies); 移到 BaseService.fetch.stuffs(function() 之外,它记录了 undefined。如何让 ctrl.stuffies 变为 BaseService.stuffies

您正在像使用服务一样使用工厂。

让您的工厂自行调用(初始化)它的 self.fetch 函数,然后在构建您的控制器时,将控制器的 stuffies 变量设置为等于工厂的 stuffies 变量。

编辑:

如果您只想一次性初始化部分数据,您可以只自行调用您想要初始检索数据的函数。

然后您可以在路由中使用解析来在命中特定路由时初始化更多数据。

不需要对 $http 服务使用回调,因为它 returns 承诺:

//.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 错误执行任何操作。错误将在 promise 中自动结转。

然后在控制器中从 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;
});

有关详细信息,请参阅


I changed your service to a factory and made it this: and used it this way:

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)?


Sorry, the factory is

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

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