订阅从函数返回的 Observable 仅在第一次有效
Subscribing to Observable returned from a function only works the first time
我无法让我的函数 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());
}
原来问题出在我不知道什么时候.subscribe什么时候.map;主题也是不必要的。更改 returnData 对地图的订阅是持续命中 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;
}
}
我无法让我的函数 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());
}
原来问题出在我不知道什么时候.subscribe什么时候.map;主题也是不必要的。更改 returnData 对地图的订阅是持续命中 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;
}
}