你肯定你不能簡單地使用組件和服務來實現這一目標?當你創建一個Angular2組件時,你可以將你的「邏輯」和模板代碼放在兩個不同的文件中,因此可以隨時修改你的模板(UI /主題),而不會影響「邏輯」。然後,您可以創建警報服務來管理其他組件和警報組件之間的通信。下面是一個例子...
對於一個部件警示你可以有兩個單獨的文件altert.html和alert.ts - 所有的UI(HTML)代碼走了進去alert.html和所有邏輯應是alert.ts ...您的代碼將然後類似於下面:
通知模板:alert.html
<div id="card-alert" *ngIf="alertMessage != "" && alertMessage != null">
<p>ALERT: {{ alertMessage }}</p>
</div>
警報邏輯:alert.ts
import {Component} from '@angular/core';
import {CustomAlertService} from './alert.service';
@Component({
selector: 'alert',
templateUrl: './alert.html'
})
export class CustomAlert {
alertSubscription: any; // this will allow you to reference the subscription in order to be able to unsubscribe later
alertMessage: String;
constructor(private alertService: CustomAlertService) { // you could also have an alert service hooked up here
this.alertSubscription = this.alertService.alertMessage$.subscribe(
message =>
this.alertMessage = message; // update current alert message to be displayed
);
}
ngOnDestroy() {
// you want to unsubscribe when component is destroyed to prevent potential memory leak
this.alertSubscription.unsubscribe();
}
}
現在需要提醒服務,請參閱下文。我不會在這方面解釋太多,因爲在這篇SO文章中標記爲:Delegation: EventEmitter or Observable in Angular2。
警報邏輯(服務):alert.service.ts
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
@Injectable()
export class CustomAlertService {
alertMessage$: Obersvable<string>;
private _observer: Observer;
constructor() {
this.alertMessage$ = new Observable(observer =>
this._observer = observer).share();
}
setAlertMessage(alert: String) {
this._observer.next(alert)
}
}
那麼你的同事就只會在應用程序內的一些高層次的CustomAlert組件。他們想要顯示警報的特定組件內部,則可以簡單地注入CustomAlertService並通過調用CustomAlertSercice的setAlertMessage(),這將反過來通知您的CustomAlert組件,它會使警報更新警報消息...