【问题标题】:RxJs Subject error - cannot read property 'subscribe' of undefinedRxJs 主题错误 - 无法读取未定义的属性“订阅”
【发布时间】:2017-07-22 21:01:50
【问题描述】:

在返回Observable 的服务方法中,我试图通过Subject 通知组件操作已完成。

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' ) );
  }

这就是组件监听Subject的方式:

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

但我收到一条错误消息,提示主题(已完成)未定义。我做错了什么?

【问题讨论】:

    标签: angular typescript rxjs subject-observer


    【解决方案1】:

    你没有正确初始化completedSubject

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

    Demo@Ompurdy

    【讨论】:

    • 我正要说这个:为你点赞 :) plunker demonstrating it 给任何想要测试的人
    • 谢谢伙计,我在答案中添加了它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 2018-10-05
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多