2016-12-27 61 views
0

我已經給出了一個示例代碼,我想給用戶數組添加一個元素。當我控制檯登錄用戶對象時,我得到一個包含1個元素的數組,但它有3個資源對象,一個promise和一個$ resolved屬性。有人可以解釋我在這裏失蹤的內容嗎?資源操作的默認設置以角度返回,我該如何修改返回的資源?

/*@ngInject*/ 
    constructor(User, Auth, $state, $uibModal, $scope) { 
     this.Auth = Auth; 
     this.$state = $state; 
     this.$uibModal = $uibModal; 
     this.$scope = $scope; 

     this.newUser = {name: "New User", email: "[email protected]", password: "gg"}; 
     this.users = User.query(); 
     this.users.push(this.newUser); 
     console.log(this.users); 

     this.$scope.$watch('this.user', function(newUser) { 
     console.log("entered watch"); 
     var val = this.users.indexOf(newUser); 
     if(val == this.users.length - 1) { 
      this.openNewUser(); 
     } 
     }); 

    } 

回答

0

你唯一缺少的是一個事實,即調用User.query()是異步的,這意味着返回的值是在稍後的時間填充。

你需要一個回調連接到查詢的承諾(this.users.$promise)如果要執行的代碼是依賴於this.users

例子:

//First get the users 
var self = this; 
this.users = User.query(); 
this.users.$promise.then(function(){ 
//Do stuff with the user list 
self.users.push(this.newUser); 
}); 
+0

我試圖做到這一點的成功裏面函數,正如你所顯示的,但它表示'this.users.push()'的'this'在它內部是未定義的。這裏發生了什麼,我該如何解決它? – Kindman

+0

我的不好。我習慣es6。我已經更新了我的回答 –

+0

其實我想在es6中使用它,但是我以前面的方式解決了範圍問題。我試圖解決它,但我不認爲我理解範圍問題。 – Kindman