2017-06-12 29 views
0

我對調用服務方法的控制器有一個操作。該服務方法是一個燼數據查詢。我需要將包含在該餘燼數據有效載荷中的消息返回給控制器(將其打印到屏幕上)。ember:承諾一個調用服務方法的控制器操作

我很難弄清楚如何讓控制器動作(功能)「等待」服務方法完成。

控制器動作:在我要等待該響應的服務

// controller action 
processCoupon() { 
    // the service method I want to wait for the response for 
    let messageObject = DS.PromiseObject.create({ 
     promise: this.get('cart').processCoupon() 
    }); 

    // the message 
    messageObject.then(response => { 
     let promo_message = messageObject.get('promo_message'); 
     if (promo_message.message && promo_message.alert) { 
      if (!promo_message.success) { 
       // show error message in alert with ember-cli-notifcations 
      } else { 
       // show success message in alert with ember-cli-notifcations 
      } 
     } 
    }); 
}, 

方法:

// service method syncs cart info (containing promo) with the backend 
// promo_message is in the response payload 
processCoupon() { 
    return this.get('store').findRecord('cart', get(this, 'cartObj.id')).then(cart => { 
     cart.save().then(newCart => { 
      set(this, 'cartObj', newCart); // sets response to property on service 
      return newCart.get('promo_message'); 
     }); 
    }); 
}, 

中承諾的「反應」是空的,而MessageObject本身具有無內容。所以我在這裏做錯了事(這可能會誤解承諾)。

我搞砸了RSVP的承諾,並沒有做好。我錯過了什麼,還是有更好的方法來做到這一點?

回答

1

你的服務方法應該返回一個承諾。然後你可以像這樣使用它:this.get('cart').process().then((response) => {/*your code working with service's response*/});

你也應該知道,如果你使用了ember數據,它將返回一個模型實例,而不是你的後端的原始響應。

而且,爲了回覆承諾,您需要將您的服務方法包裝在

相關問題