e(1):更新了原始问题以解决拼写错误的代码
e(2):尝试使用JSON.stringify()'数据在' createContent()'中被推送到我的JSON对象中。没有运气。
e(3):根据要求添加了 plnkr :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运行不正常。
如果我更改了这些内容,以便我在组件中有一个数组,请订阅服务&#39; contents $&#39;填充阵列,然后它没什么大不了的。
当我记录所调用的服务和函数的输出时,一切都很花哨。我遇到的唯一症状是&#34; * ngFor&#34;似乎没有正确处理流。这是显而易见的事情,不是吗?
答案 0 :(得分:2)
问题是Angular会评估
<h1 *ngFor="let item of contents$ | async">{{ item.name }}</h1>
仅在下次更改检测时运行。
因为
this._service.load();
执行同步,在Angular有机会订阅之前发出事件。
例如,如果您使用BehaviorSubject
代替Subject
向新订阅者发出最后一次发布的值,那么您将获得所需的行为。
您也可以在致电this._service.load();
之前手动调用变更检测,或致电this._service.load();
延迟发货
但这取决于您的具体要求。
答案 1 :(得分:0)
我发现您的代码存在潜在问题:
createContent(item: Content): void {
this._data.contents$.push(item);
this._contents$.next(this._data.contents$);
}
我会改用以下内容:
createContent(item: Content): void {
this._data.contents.push(item); // <----
this._contents$.next(this._data.contents); // <----
}