이것을 달성하기 위해 구성 요소와 서비스를 단순히 사용할 수는 없습니까? Angular2 구성 요소를 만들 때 "논리"와 두 개의 다른 파일에있는 템플릿 코드를 가질 수 있으므로 "논리"에 영향을주지 않고 항상 원하는대로 템플릿 (UI/테마)을 수정할 수 있습니다. 그런 다음 다른 구성 요소와 경고 구성 요소 간의 통신을 관리하는 경고 서비스를 만들 수 있습니다. 다음은 예제입니다 ...
구성 요소 경보의 경우 두 개의 개별 파일 altert.html과 alert.ts가있을 수 있습니다. 모든 UI (html) 코드는 alert.html 내부에 있으며 모든 논리는 alert.ts에 있습니다.
ALERT 템플릿 : : ALERT의 LOGIC
<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();
}
}
경고 서비스는 아래를 참조하십시오. 이것에 관해서는 여기에있는 문서 (Delegation: EventEmitter or Observable in Angular2)에 잘 설명되어 있기 때문에 여기서는 그다지 설명하지 않겠습니다.
ALERT의 LOGIC (서비스) : 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를 삽입하고 경고를 렌더링하는 CustomAlert 구성 요소에 통보 할 CustomAlertSercice에서 setAlertMessage()를 호출하여 경고 메시지를 업데이트 할 수 있습니다.