Angular:当变量异步更改时,视图不更新

时间:2018-06-16 05:47:31

标签: angular angular5 observable subscription

这里我订阅了App.Component.ts中Notification服务的通知$。每件事情都很顺利,我在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}`);
    }
}

1 个答案:

答案 0 :(得分:1)

如果以后反映出更改,则必须是更改检测问题。 Http响应回调通常后面跟着更改检测运行,但是如果你有ChangeDetectionStrategy.OnPush,你的组件将不会被标记为check。你可以明确地这样做。只需注入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(); 
          });
      }
相关问题