2015-10-25 111 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方法)设置计算属性,该组件可以切换错误消息。

只要您设置了通知,您的组件就会看到它正在监视的属性已更改并显示/隐藏您的通知。

相关问题