异步管道无法呈现可观察到的 [英] Async Pipe Fails to Render Observable
问题描述
e(1):更新了代码以解决原始问题中的错字.
e(2):尝试将数据"JSON.stringify()"推送到"createContent()"中的JSON对象中.没有运气.
e(3):根据要求添加了 plnkr : http://plnkr.co/edit/j024MYCQbypAGaf762fT
e(1): Updated code to address typo's in original question.
e(2): Attempted to 'JSON.stringify()' the data pushed into my JSON object in 'createContent()'. No luck.
e(3): Added plnkr as requested: http://plnkr.co/edit/j024MYCQbypAGaf762fT
我有模特...
class Content {
constructor(public name: string) { }
}
我有服务...
class ContentService {
private _contents$: Subject<Content[]>
= new Subject<Content[]>();
get contents$(): Observable<Content[]> {
return this._contents$.asObservable();
}
private _data: { contents: Content[] } = { contents: [] };
...
load(): void {
createContent(new Content("Test Content..."));
}
createContent(item: Content): void {
this._data.contents.push(item);
this._contents$.next(this._data.contents);
}
}
我有一个组件...
@Component({
...
template: `
<h1 *ngFor="let item of contents$ | async">{{ item.name }}</h1>
`
})
class ContentListComponent {
contents$: Observable<Content[]>;
constructor(private _contentService: ContentService) { }
ngOnInit(): void {
this.contents$ = this._contentService.contents$;
this._contentService.load();
}
}
简而言之,我不明白为什么组件中的Observable无法正常运行.
Simply put, I don't understand why the Observable in my component is not functioning correctly.
如果我改变这些位置,例如在组件中有一个数组,则订阅服务"contents $"来填充该数组,那么这没什么大不了的.
If I change these around, such that I have an array in the component, subscribe to the service 'contents$' to populate the array, then it's no biggie.
当我记录服务和函数调用的输出时,所有内容也很花哨.我遇到的唯一症状是"* ngFor"似乎没有正确处理流.很明显,不是吗?
When I log the output of the service and functions called, everything is also dandy. The only symptom I am experiencing is that the "*ngFor" does not appear to be properly handling the stream. It's something obvious, isn't it?
推荐答案
问题是Angular会评估
The problem is that Angular evaluates the
<h1 *ngFor="let item of contents$ | async">{{ item.name }}</h1>
仅在下次运行更改检测时.
only when change detection runs the next time.
因为
this._service.load();
已执行同步,该事件在Angular有机会订阅之前发出.
is executed sync, the event is emitted before Angular had a chance to subscribe.
例如,如果您使用BehaviorSubject
而不是Subject
来向新的订户发送最后一个发出的值,那么您将获得所需的行为.
If you for example use a BehaviorSubject
instead of Subject
which emits that last emitted value to new subscribers, then you get the desired behavior.
您还可以在调用this._service.load();
或延迟调用this._service.load();
之前手动调用更改检测.
但这取决于您的特定要求.
You could also invoke change detection manually before calling this._service.load();
or call this._service.load();
delayed
but that depends on your specific requirements.
这篇关于异步管道无法呈现可观察到的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!