これを達成するために単にコンポーネントとサービスを使用することはできませんか? Angular2コンポーネントを作成するときは、 "ロジック"と2つの異なるファイルにテンプレートコードを含めることができます。したがって、 "ロジック"に影響を与えずに、テンプレート(UI /テーマ)をいつでも変更できます。アラートサービスを作成して、他のコンポーネントとアラートコンポーネント間の通信を管理することができます。ここに例があります...
アラートの場合、altert.htmlとalert.tsという2つの別々のファイルがあります。すべてのUI(html)コードはalert.html内にあり、すべてのロジックはalert.tsに入ります
ALERTテンプレート:ALERTロジック
<div id="card-alert" *ngIf="alertMessage != "" && alertMessage != null">
<p>ALERT: {{ alertMessage }}</p>
</div>
alert.html:...あなたのコードは、以下のようになります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ロジック(サービス):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()を呼び出します。このアラートメッセージは、CustomAlertSerciceに対して通知します。