【问题标题】:Subscribing to Observable returned from a function only works the first time订阅从函数返回的 Observable 仅在第一次有效
【发布时间】:2017-11-24 21:42:44
【问题描述】:

我不能让我的函数 getData 多次工作,第一次使用字段名称“a”调用 getData,数据从 returnData 返回,并且 getData 的 .subscribe 内的块被命中。第二次使用字段“b”调用 getData,returnData 内部的所有内容都按预期工作,但是 getData 的 .subscribe 内部的块根本没有命中。

private getData(field: string): void { 
  this.returnData(field)                                 
    .subscribe((data) => {
    //Handle Data
    //This block is only hit the first time getData is called
  });}

private returnData(field: string): Observable < SomeObj > {         
  let subj: Subject < SomeObj > = new Subject < SomeObj > ();      
  const obj: SomeObj = new SomeObj(field); 
  this.someDataServive.someFunction(field)
    .subscribe(
    (data) => {
      //set properties on obj from data and emit obj
      subj.next(obj);
      //This block is always hit every time getData is called, and the 
      // obj returned from here is correct
     },                                                            
    (err) => {
      subj.next(obj);
    });                                                             
  return (subj.asObservable());                                        
}

【问题讨论】:

标签: typescript rxjs angular2-observables


【解决方案1】:

原来问题在于我不了解何时使用 .subscribe 以及何时使用 .map;主题也是不必要的。只需更改 returnData 对 map 的订阅,就可以始终如一地点击 returnData 中的 .subscribe 块。

private returnData(field: string): Observable < SomeObj > {              
  const obj: SomeObj = new SomeObj(field); 
  return this.someDataServive.someFunction(field)
    .map(
    (data) => {
      obj.data = data;
      return obj;
    }                                                                                                    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2017-02-17
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多