【发布时间】:2019-08-22 13:51:01
【问题描述】:
我有两种服务:一种依赖于另一种。服务 A 进行 http 调用以获取数据。服务 B 实际使用该数据。
服务 A:
@Injectable({
providedIn: 'root'
})
export class ServiceA {
data: MyData;
getData(): Observable<MyData> {
return this.http.get<Mydata>('http://some.url')
.pipe(
tap((data: MyData) => {console.log(`got data');})
)
);
};
}
服务 B:
@Injectable({
providedIn: 'root'
})
export class ServiceB {
obs = Observable<MyData> = new Observable<MyData>();
processedData: string[];
constructor(private serviceA: ServiceA) {
this.obs = this.serviceA.getData();
this.obs.subscribe(
data => {this.processedData = process(data)},
error => { /*process error*/ },
function() { /* maybe mark flag here? */}
);
}
process(endpointData) {
// Do some business logic to endpointData
this.processedData = endpointData;
}
processedData() {
// The first time this is called, the observable hasn't completed
}
}
服务 B 的客户端将调用 processesData()。只是好奇如何优雅地等待 processData() 中的 observable。我的非异步方面想检查 observable 的 finally 部分是否已被调用。如果是这样,只需使用 this.processedData。如果不是……那又怎样?我想我可以只订阅一次,在处理数据中,并且只在第一次调用时。这似乎仍然不太正确。想法?
【问题讨论】:
-
您是否尝试过使用
toPromise()将 observable 转换为可以等待的单个调用? -
这可能会有所帮助。 stackoverflow.com/questions/44593900/…
-
@chrismclarke 我确实考虑过 toPromise() 但我读过的大多数地方都建议不要将其用作对问题的全面回应。
标签: angular rxjs observable