我不能让函数get data工作多次,第一次用字段名“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());
}

最佳答案

结果发现问题出在我不知道什么时候去订阅什么时候去地图上,而且主题是不必要的。更改returndata的subscribe to 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;
    }
}

10-06 12:22