角度:当变量异步更改时视图不更新



在这里,我在App.Component.ts中订阅通知服务的通知$。一切都进展顺利,我已经更改了 App.Component.ts 的 ngOnInit 中的值,但它的视图没有相应地渲染/更新。

但是当转到另一个视图时,我发现视图已相应更改(但不是同时其值更改(。

App.Component.ts :

export class AppComponent implements OnInit {
notification: string;
public showNotification: boolean = true;
constructor(private notificationService: NotificationService) {}
ngOnInit() {  
this.notificationService
.notification$
.subscribe(message => {
debugger;      // message is here 
this.showNotification = true;
this.notification = message;       
});
}
}

通知服务 :

import { Injectable } from '@angular/core';    
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';    
import 'rxjs/add/operator/publish';
import { Subject } from 'rxjs/Subject';    
@Injectable()
export class NotificationService {
private _notification: BehaviorSubject<string> = new BehaviorSubject(null);
readonly notification$: Observable<string> = this._notification.asObservable().publish().refCount();    
constructor() { }    
notify(message) {        
this._notification.next(message);
//setTimeout(() => this._notification.next(null), 3000);
}    
}

错误服务 :

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { Router } from '@angular/router';    
import * as StackTraceParser from 'error-stack-parser';   
import { NotificationService } from '../_common/notification.service';    
@Injectable()
export class ErrorsService implements ErrorHandler {
constructor(
private injector: Injector
) { }
handleError(error: Error | HttpErrorResponse) {       
const notificationService = this.injector.get(NotificationService);        
if (error instanceof HttpErrorResponse) {     
return notificationService.notify(`${error.status} - ${error.message}`);
}
}

如果更改稍后反映,则一定是更改检测问题。 Http 响应回调通常之后是更改检测运行,但如果你有 ChangeDetectionStrategy.OnPush,你的组件不会被标记为检查。您可以显式执行此操作。只需注入实例ChangeDetectorRef并在必要时调用其markForCheck()方法:

constructor(private notificationService: NotificationService, private cd: ChangeDetectorRef) {}
ngOnInit() {  
this.notificationService
.notification$
.subscribe(message => {
debugger;      // message is here 
this.showNotification = true;
this.notification = message;
this.cd.markForCheck();
// if markForCheck didn't help, try to trigger change detection mannually:
// this.cd.detectChanges(); 
});
}

最新更新