等待 observable 中的其他 observable 响应。角度异步
我想实现什么目标?
- 我有多个组件具有几乎相同的检查和数据操作..我想将它们转移到可观察中..
- 我在我的服务中创建了一个可观察名称“getData”...
- 不同的是“getdata”有一个 if 检查.. - > 如果本地存储有数据则返回数据。 如果没有,则从 api 调用(getbyid)请求数据,然后操作它并返回数据。
注意:我们无法更改 getbyid()。他们都在同一个服务中。
API
getbyid(id: any): Observable<any> {
return this.http.post<any>(this.serverurl, id )
.pipe(tap((res) => { return res }));
}
我的代码
getData(origin: any, id:number):Observable<any> {
let data= new BehaviorSubject({});
if(origin=='main page'){
let localstorage= this._aes.getItem('localstorage')
if(!localstorage){
console.log('before api');
this.getbyid(id).subscribe(res=>{
console.log('res',res);
data.next(res)
return data.asObservable()
})
console.log('after api');
}else{
data.next({data:payload})
return data.asObservable()
}
}
}
当前场景:它只是点击 getbyid 而不是等待响应并继续...如果我们以某种方式让它等待响应,这可以解决。
What I am trying to achieve?
- I have multiple components having almost same checks and data manipulation.. I wanted to shift them in a observable..
- I created an observable name "getData" in my service...
- the twist is "getdata" has a if check.. ->
if the local storage has data then return data.
if not then request data from api call(getbyid) then manipulate it and return data..
NOTE: we can't change the getbyid(). and they both are in same service.
API
getbyid(id: any): Observable<any> {
return this.http.post<any>(this.serverurl, id )
.pipe(tap((res) => { return res }));
}
MY CODE
getData(origin: any, id:number):Observable<any> {
let data= new BehaviorSubject({});
if(origin=='main page'){
let localstorage= this._aes.getItem('localstorage')
if(!localstorage){
console.log('before api');
this.getbyid(id).subscribe(res=>{
console.log('res',res);
data.next(res)
return data.asObservable()
})
console.log('after api');
}else{
data.next({data:payload})
return data.asObservable()
}
}
}
CURRENT scenario: its just hitting the getbyid and not waiting for the response and proceed... if somehow we make it to wait for the response this can be solved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下你不需要BehaviorSubject。
像这样的东西应该可以工作(我认为“有效负载”是您存储的内容?):
如果设置了有效负载,我们将返回一个可观察的值。如果没有,则为带有后端调用的可观察对象。
在这两种情况下,您都必须从调用 getData 方法的位置进行订阅并等待响应。
You don't need BehaviorSubject in this kind of scenario.
Something like this should work (I supposed "payload" is the content of your storage ?):
If
payload
is set, we return an observable with it. If not, an observable with a backend call.In both cases, you have to subscribe from where you call
getData
method and wait response.