Does anyone why this code (initializing a value from Subject) does not work? Is there a bug or by design? What am I doing wrong?
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>
It seems like a timing issue, if you throw it in a setTimeout it works.
setTimeout(() => this.itemSupplier$.next(this.items), 0)
EDIT
It is actually a better idea to use BehaviorSubject. This will provide the last value when it is subscribed to.