是否可以调用Subscribe
方法两次?
我正在尝试构建 api 工厂,它在工厂中保存数据,但该数据可以在每次 ajax 调用时由不同的组件使用。
工厂
export class api {
result = [];
constructor (protected http: Http) { }
getData ()
{
return this.http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
}
}
测试组件,再次调用subscribe
方法
export class TestPage {
showListResult;
constructor (protected api: api) {
this.api.getData().subscribe(res => this.showListResult = res)
}
}
最佳答案
您可以返回新的 Observable 包装器。这样的事情应该有效:
import {Observable} from 'rxjs/Observable'
export class api {
result = [];
constructor (protected http: Http) { }
getData () {
return new Observable(observer => {
this.http.get('./friends.json')
.map((res: Response) => res.json())
.subscribe(res => {
this.result = res;
observer.next(res);
observer.complete();
});
});
}
}
关于typescript - Angular2 Http 双订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397710/