あなたの効果を達成するには、いくつかの方法があります。この最初のやり方は、私が思うには最も簡単なものです。これまでのところ、あなたがこれまでかなりきついことをしています。これらのすべては、サービスが最後に処理した値を表示するようにテンプレートに直接指示します。これはお勧めできません。
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);
}
}
我々はまた、観測を使用してこれを行うことが
は、ソースのこの回答を参照してください。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);
}
}
それは完全にあなたがどのように変更することができ、2つの成分を分離するように、第2の方法は、おそらく良いだろうプロセスサービスは他のコードを変更することなく完全に動作します。