如何使事件触发Angular2中的多个组件
Posted
技术标签:
【中文标题】如何使事件触发Angular2中的多个组件【英文标题】:How to make an event trigger multiple components in Angular2 【发布时间】:2016-10-18 15:19:43 【问题描述】:我有一个输入组件、一个输出组件和一个处理服务。我希望用户输入一个字符串,并让处理服务将处理后的消息输出到输出组件。我遇到的麻烦是从处理服务获取处理后的消息。 这是我目前所拥有的:
<input class="input" type ="text"[(ngModel)]="text" (keyup.enter)="process(text)">
export class InputComponent
text: String;
constructor(private processService: ProcessService)
process(text)
this.processService.process(text);
export class ProcessService
processedMsg: string;
process(msg)
this.processedMsg = "a message thats processed";
getMessage()
return this.processedMsg;
export class OutputComponent
output: string;
constructor(private processService: ProcessService)
getOutput()
this.output = this.processService.getMessage();
我怎样才能做到当用户按下回车时,输入被处理,并被提供给输出?谢谢。
【问题讨论】:
【参考方案1】:有几种方法可以实现您想要的效果。第一种方法是我认为最容易掌握的方法,它非常接近你迄今为止所拥有的。这一切都是直接告诉模板显示服务上次处理的值,不推荐。
import Component, Injectable from '@angular/core';
@Injectable()
class ProcessService
processedMsg: string = "";
process(msg)
this.processedMsg = "Processed: \""+msg+"\"";
@Component(
selector: 'output',
template: '<span>processService.processedMsg</span>'
)
class OutputComponent
constructor(public processService: ProcessService)
@Component(
selector: 'my-app',
directives: [OutputComponent],
providers: [ProcessService],
template: `
<input class="input" type ="text" [(ngModel)]="text" (keyup.enter)="process(text)"><br>
<output></output>
`
)
export class AppComponent
text:string;
constructor(private processService: ProcessService)
process(text)
this.processService.process(text);
我们也可以使用 Observables 来做到这一点,请参阅这个答案的来源:Delegation: EventEmitter or Observable in Angular2
import Component, Injectable, OnInit, OnDestroy from '@angular/core';
import BehaviorSubject from "rxjs/BehaviorSubject";
import Subscription from 'rxjs/Subscription';
@Injectable()
class ProcessService
private _processedMsgSrc: BehaviourSubject<string> = new BehaviorSubject<string>("");
processedMsg = this._processedMsgSrc.asObservable();
process(msg)
this._processedMsgSrc.next("Processed: \""+msg+"\"");
@Component(
selector: 'output',
template: '<span>output</span>'
)
class OutputComponent implements OnInit, OnDestroy
output:string;
private _subscription:Subscription;
constructor(public processService: ProcessService)
ngOnInit()
this.subscription = this.processService.processedMsg.subscribe(
msg => this.output = msg
);
ngOnDestroy()
// stop the subscription when the component is destroyed
this.subscription.unsubscribe();
@Component(
selector: 'my-app',
directives: [OutputComponent],
providers: [ProcessService],
template: `
<input class="input" type ="text" [(ngModel)]="text" (keyup.enter)="process(text)">
<br>
<output></output>
`
)
export class AppComponent
text:string;
constructor(private processService: ProcessService)
process(text)
this.processService.process(text);
第二种方式可能会更好,因为它将两个组件完全分开,允许您完全更改流程服务的工作方式,而无需更改任何其他代码。
【讨论】:
以上是关于如何使事件触发Angular2中的多个组件的主要内容,如果未能解决你的问题,请参考以下文章