簡體   English   中英

在Angular中解決承諾后重新制作請求

[英]Remake request after promise resolves in Angular

我覺得這里缺少一些簡單的東西。 我的目標是能夠訪問服務中的數據(該服務從端點獲取數據),但以后能夠通過重新對端點執行ping操作來更新存儲的數據。

.service('myService', function($http) {
    var self = this;    

    this.myData = {};

    this.getItem = function() {
        return $http.get('/path/to/endpoint')
            .then(function(res) {
                self.myData = res.data;  // data looks like: { x: 1, y: 2}
            }); 
    };
})

.controller('mainCtrl', function($scope, myService) {
    myService.getItem();
    $scope.data = myService.myData;

    window.logService = function() {
        console.log(myService);  // { getItem: function(){...}, data: {x: 1, y: 2} }
    };
});

<div ng-controller="mainCtrl">{{data.x}}</div> <!-- Does not update with the data returned from the promise -->

這似乎沒有任何意義。 如果在諾言返回后點擊window.logService() ,則可以在正確的位置清楚地看到數據,但視圖不會更新。

即使您重新分配值,Angular也會監視{}引用。

嘗試在回調中使用angular.copy() ,以便觀察的對象得到更新,並且視圖正確更新。

.then(function(res) {
    angular.copy( res.data, self.myData);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM