angulartypescriptrxjssubject-observer

RxJs Subject error - cannot read property 'subscribe' of undefined


In my service method that returns Observable I'm trying to notify the component via Subject that an action completed.

completed: Subject<boolean>

  constructor(private http: Http) {

  }

  loadItems(): Observable<FrontItemDto[]> {
    return this.http.get ( `${ServiceSettings.ApiUrl}/front` )
      .map ( res => {
        res.json ();
        if ( res.json () ) {
          this.completed.next ( true );
        }
      } )
      .catch ( (error: any) => Observable.throw ( error.json ().error || 'Server error' ) );
  }

This is how the component is listening to Subject:

ngOnInit(): void {
    this.getItems();
    this.sub = this.dataService.completed.subscribe(completed => {
      if (completed) {
        this.show = false;
      }
      });
  }

But I'm getting an error saying that Subject (completed) is undefined. What am I doing wrong?


Solution

  • You have not initialized completed Subject correctly

    completed = new Subject<boolean>(); //it should have parenthesis at the end
    

    Demo by @Ompurdy