2014-10-19 63 views
3

在爲我的應用程序構建登錄功能原型時,我使用路由根據給定的用戶名查詢商店。如果找不到該用戶名,我的API將返回一個帶有消息屬性的對象。這裏是該路線:獲取查詢屬性

App.LoginRoute = Ember.Route.extend({ 
    actions: { 
     getUsername: function(username){ 
      this.store.find('user', {username: username}).then(function(user){ 
      var eid = user.get('eid'); 
      console.log(eid); 
      if (eid) { 
       self.controller.send('transition', "index"); 
       } 
      else { 
       self.controller.set('model', "Oops! That's not right.");} 
       }); 
      } 
    } 
});` 

如果用戶名存在於數據庫中,API將發回用戶對象。如果用戶名存在,它可以很好地加載到商店中,我可以在Ember Inspector中的數據下看到記錄。但是,我不知道如何獲取該用戶對象的屬性。

.then我正在傳遞返回的信息,並試圖在那個上調用.get,但總是返回undefined。

什麼是從store.find('store', {query})返回任何內容的正確方法?

回答

2

通過查詢查找返回一個集合。

this.store.find('user', {username: username}).then(function(userCollection){ 
    // this would be the user if it existed 
    var user = userCollection.get('firstObject'); 
    self.controller.send('transition', "index"); 
});  

你或許應該返回404錯誤代碼,而不是當用戶不存在有效的響應,然後打的承諾的失敗部分。

this.store.find('user', {username: username}).then(function(userCollection){ 
    // this would be the user if it existed 
    var user = userCollection.get('firstObject'); 
    self.controller.send('transition', "index"); 
}, function(){ 
    // failure happened 
    self.controller.set('model', "Oops! That's not right.");} 
});  
+0

感謝您糾正我對查找查詢返回結果的理解!我一直在爲此摔跤幾天。您的解決方案完全按照我需要的方式工作。謝謝! – carebdayrvis 2014-10-20 00:02:06

+1

當你對返回的內容感到困惑時,你總是可以使用'.toString()'來告訴你返回什麼類型的模型。在Kingpin2k的例子中,在'.then()'你會做'console.log(userCollection.toString())'這會告訴你這是一個集合。 – 2014-10-20 04:40:39

+0

爲什麼返回的內容沒有任何提示?我無法從中得到任何東西。我想能夠知道返回的細節,但是'userCollection.get('firstObject')'返回undefined。 – carebdayrvis 2014-10-20 05:52:00