Does anyone know 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.
I was having the same issue and setTimeout was effective as a solution, but found that I did not need to use setTimeout if an Observable to which the Subject's switchMap() method output was assigned was subscribed to PRIOR to calling next(). In your example, it might require creating an Observable, subscribing and updating the property directly rather than using the async pipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With