有谁知道为什么这段代码(从主题初始化一个值)不起作用?是否存在错误或设计使然?我究竟做错了什么?
ts
import { Component, OnInit } from '@angular/core';
import { Subject } from "rxjs";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.styl']
})
export class AppComponent implements OnInit {
itemSupplier$: Subject<any[]> = new Subject<any[]>();
items: any[] = [
{name: 'Item 1', value: 'item1'},
{name: 'Item 2', value: 'item2'},
];
ngOnInit(){
this.itemSupplier$.next(this.items);
}
}
html
<ul>
<li *ngFor="let item of itemSupplier$ | async">{{item.name}}</li>
</ul>
这似乎是一个计时问题,如果你将它放入 setTimeout 中,它就会起作用。
setTimeout(() => this.itemSupplier$.next(this.items), 0)
EDIT
使用BehaviorSubject 实际上是一个更好的主意。这将在订阅时提供最后一个值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)