我有一個MessageService,它使用ReplaySubject類在用戶執行特定操作(如編輯某些內容)時觸發事件。因此,事件將從BaseService類和MainComponent類中觸發,該類負責保存管理面板模板以偵聽事件,並且在收到消息時將顯示在模板中。我也有一個BaseComponent類,我的所有組件都從它延伸並且這個類有一個消息字段來保存消息字符串。 BaseComponent類不是單例,所以顯然每個組件都會顯示它將被實例化。我的問題是當用戶在組件之間導航時,消息仍將被放置。即使它的值爲空,但消息不會消失。Angular 2查看變量更改後不更新
我MessageService類:
import {ReplaySubject} from 'rxjs/ReplaySubject';
export class MessageService{
public messageSource;
public messageEvent;
constructor(){
this.messageSource = new ReplaySubject(1);
this.messageEvent = this.messageSource.asObservable();
}
public setMessage(message){
this.messageSource.next(message);
}
我MainComponent類:
export class MainComponent extends BaseComponent{
constructor(public router:Router,public authService:AuthService,
public messageService:MessageService){
super(router);
}
ngOnInit(){
this.messageService.messageEvent.subscribe(msg => {
this.message = msg;
});
}
我的模板:
<div class="row" *ngIf="message">
<div class="alert alert-success" *ngIf="message.type=='success'">
<button data-dismiss="alert" class="close" type="button">×</button>
{{message.message}}
</div>
<div class="alert alert-danger" *ngIf="message.type == 'error'">
<button data-dismiss="alert" class="close" type="button">×</button>
{{message.message}}
</div>
</div>
和我BaseComponent類:
export class BaseComponent {
public permission = new PermissionController();
public data;
public route = null;
public invalidateData=false;
public invalidateObject = null;
public message = null;
constructor(public router:Router){
console.log('message : ',this.message);
}
/**
* Handles response received from api call.
* @param Response
**/
public handleResponse(response){
if(response){
if(this.route){
this.router.navigate(this.route);
}
this.data = response;
}
}
public handleMessage(response){
if(response){
this.invalidateDataArray();
}
}
private invalidateDataArray(){
if(this.invalidateData){
var index = this.data.indexOf(this.invalidateObject);
this.data.splice(index,1);
}
return true;
}
public navigateTo(url:string){
this.router.navigate([url]);
}
}
和我BaseService:
private setMessage(type){
if(this.shouldShowMessage){
switch (type) {
case "done":
this.messageService.setMessage({type:'success',message:'Operation Successfully Completed'});
break;
case 'fail':
this.messageService.setMessage({type:'success',message:'Operation Failed.'});
break;
}
}
}
你在哪裏提供'MessageService'和'BaseService'?什麼屬性沒有更新? –
消息服務是單例,BaseService是所有服務類從中擴展的基類。 –
提供'MessageService'在哪裏? –