我无法让我的函数 getData 工作不止一次,第一次使用字段名称“a”调用 getData 时,数据从 returnData 返回,并且 getData 的 .subscribe 内的 block 被命中。第二次使用字段“b”调用 getData 时,returnData 中的所有内容都按预期工作,但是根本没有命中 getData 的 .subscribe 中的 block 。
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());
}
最佳答案
原来问题出在我对什么时候.subscribe 什么时候.map 缺乏理解;主题也是不必要的。更改 returnData 对 map 的订阅是一致命中 returnData 中的 .subscribe block 所需的全部。
private returnData(field: string): Observable < SomeObj > {
const obj: SomeObj = new SomeObj(field);
return this.someDataServive.someFunction(field)
.map(
(data) => {
obj.data = data;
return obj;
}
}
关于typescript - 订阅从函数返回的 Observable 仅在第一次有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685364/