【问题标题】:Angular : View not updating when variable changed asynchronouslyAngular:当变量异步更改时视图不更新
【发布时间】:2018-11-25 20:59:36
【问题描述】:

这里我在 App.Component.ts 中订阅 Notification 服务的 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}`);
    }
}

【问题讨论】:

  • 发布一个完整的最小示例,在 StackBlitz 中重现该问题。
  • 尝试在 ngOnChanges 或 ngDoCheck 方法中做,这可能会解决你的问题

标签: angular angular5 observable subscription


【解决方案1】:

如果稍后反映更改,则必须是更改检测问题。 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(); 
          });
      }

【讨论】:

  • 你是在组件构造函数中注入的吗?
  • 我觉得应该这样用 this.cd.markForCheck();
  • 该死的...我忘了this。已更新。
  • 你可以试试 this.cd.detectChanges(); (在sn-p中有注释)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2019-02-28
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 1970-01-01
相关资源
最近更新 更多