【发布时间】: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