Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subject.next not firing in ngOnInit

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>
like image 579
user776686 Avatar asked Jan 15 '17 23:01

user776686


2 Answers

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.

like image 66
Steveadoo Avatar answered Oct 19 '22 07:10

Steveadoo


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.

like image 1
ajs Avatar answered Oct 19 '22 07:10

ajs