我有一个MessageService,它使用ReplaySubject类在用户执行特定操作(例如编辑某些内容)时触发事件。所以事件将从BaseService类触发,负责持有管理面板模板的MainComponent类侦听事件,当它收到消息时将显示在template.I有一个BaseComponent类,我的所有组件都从它扩展这个类有一个消息字段,用于保存消息字符串。 BaseComponent类不是单例,因此显然在每个组件上都会实例化它。我的问题是当用户在组件之间导航时,消息仍将被放置。即使它的值为空,但消息也不会消失。
我的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;
}
}
}
答案 0 :(得分:0)
更改检测的问题通常是Angular2默认只检测对象引用在属性值更改时更改时的更改。
要确保更改检测工作,请确保通过克隆对象来更改对象引用。 例如boundObject = Object.assign({},{},boundObject);
或者如果你需要深度克隆,请使用lodash。