2015-10-25 99 views
0

的組件顯示要了解有關使用服務和組件的更多信息,我試圖設置一個簡單的Flash消息樣式服務。在我的路線中,我保存了一條記錄並從服務器接收到json通知或json錯誤。由於這是一個行爲,我最終想使用應用程序範圍,我使用一個簡單的服務(注入我的路線)來處理顯示消息。在路線內,我可以撥打this.get('notification').displayMessage(msg)更新來自路由

目前服務中的displayMessage函數只是提醒消息,因爲我被困在如何創建服務可以「更新」的組件。服務如何與組件通信以便我可以發送消息並從組件模板中顯示消息?

簡檔/索引路線

user.save().then((response) => { 
    //display response.notice in the app-notification component template 
}, (response) => { 
    let errors = JSON.parse(response.errors); 
    //display response.error in the app-notification component template 
    this.get('notification').displayMessage(errors[0]); 
} 

服務

import Ember from 'ember'; 

const { Service } = Ember; 

export default Service.extend({ 

    displayMessage(msg) { 
    alert("message ---> " + msg); 
    } 
}); 

部件

??? 

分量模板

<h2 class="alert">{{message}}</h2> 

應用模板

{{app-notification message=message}} 

回答

0

在訪問的服務的方面,我喜歡他們使用的文檔的例子:http://guides.emberjs.com/v2.1.0/applications/services/

的我的購物服務被注入到需要訪問購物車的組件。

一旦你進入我的購物,你應該能夠:

  • 設置在服務通知用戶從您的路線錯誤捕獲。
  • 基於組件hasError上的Notification服務(某種hasNotification方法)設置計算屬性,該組件可以切換錯誤消息。

只要您設置了通知,您的組件就會看到它正在監視的屬性已更改並顯示/隱藏您的通知。

相關問題