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

吃可爱长大的小学妹 提交于 2019-12-06 14:26:01

问题


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?


回答1:


You have not initialized completed Subject correctly

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

Demo by @Ompurdy



来源:https://stackoverflow.com/questions/45259200/rxjs-subject-error-cannot-read-property-subscribe-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!