我面临着一个非常奇怪的问题。我在 *ngIf 中使用可观察性来显示错误以及异步管道。
问题是当 Observable 的值更新时,DOM 不会更新。它仅在我单击页面或使用键盘获得焦点时更新。
那么,我应该如何将可观察与 DOM 绑定?
我尝试了各种解决方案来绑定 DOM,使用 *ngIf、如果其他在 *ngIf、有和没有异步管道等。
这是我在HTML中的使用方式。
<div style="font-size: 0.9rem;" *ngIf="messageInfo | async"
[ngClass]="{ 'alert': message, 'alert-success': message.type === 'success',
'alert-danger': message.type === 'error' }">{{message.text}}
<span (click)="close()" style="cursor: pointer; float: right;">
<i class="material-icons icon-20 vertical-bottom">close</i>
</span>
</div>
组件代码
export class AlertComponent implements OnInit {
message: any;
messageInfo: Observable<any>;
constructor(private alertService: AlertService) {
}
ngOnInit() {
this.messageInfo = this.alertService.getMessage();
this.messageInfo.subscribe(message => {
this.message = message;
});
}
close() {
this.alertService.close();
this.message = undefined;
}
}
服务
export class AlertService {
private subject = new BehaviorSubject<any>(null);
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
if (this.keepAfterNavigationChange) {
// only keep for a single location change
this.keepAfterNavigationChange = false;
} else {
// clear alert
this.subject.next(null);
}
}
});
}
success(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({type: 'success', text: message});
// to hide message after 3 seconds.
setTimeout(() => {
this.close();
}, 3000);
}
error(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
this.subject.next({type: 'error', text: message});
// to hide message after 3 seconds.
setTimeout(() => {
this.close();
}, 3000);
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
close() {
this.subject.next(null);
}
}
我以这种方式在所有其他组件中使用它:
<alert></alert>
我希望根据可观察的值更新 UI,而无需单击或专注于页面。不幸的是,只有当我使用鼠标或键盘专注于页面时,它才会更新。
按照此处的建议更新 ngZone 内的变量:在您的情况下应该是这样的:
public constructor(private _ngZone: NgZone) {}
this.messageInfo.subscribe(message => {
this._ngZone.run(() => {
this.message = message;
});
});
https://github.com/angular/angular/issues/7381#issuecomment-191456151
如果这不起作用,您可以尝试使用:
import { ChangeDetectorRef } from '@angular/core';
public constructor(private cdr: NgZone) {}
this.messageInfo.subscribe(message => {
this.message = message;
this.cdr.markForCheck();
});
你能尝试关注吗 -
从组件中删除message
变量并删除this.messageInfo.subscribe
行并像这样更新您的模板。
<div style="font-size: 0.9rem;" *ngIf="(messageInfo | async) as message"
[ngClass]="{ 'alert': message, 'alert-success': message.type === 'success',
'alert-danger': message.type === 'error' }">{{message.text}}
<span (click)="close()" style="cursor: pointer; float: right;">
<i class="material-icons icon-20 vertical-bottom">close</i>
</span>
</div>