我正在使用 observable 进行 HTTP 请求,我想将其作为同步调用,因为我对 rxjs 很陌生。下面的代码用于执行多个调用,因此在完成所有调用后,我只需调用驱动方法。我引用了很多链接,但我无法理解,请帮助我。
ServicecallApi:
public createHttpRequests(
method: string,
url: string,
payload?: any,
params?: any,
): Observable<any> {
switch ((method).toLowerCase()) {
case 'get': return this.createHttpGet(url, params);
case 'post': return this.createHttpPost(url, payload);
default: return this.http.get('');
}
}
我的服务电话如下:
public ngOnInit(): void {
this.serviceCall.createHttpRequests('get', this.someService.getUserList, {}, {}).pipe(
map((result: Iuserlist) => {
if (result.body.statusCode === 200) {
} else {
}
}),
).subscribe();
this.serviceCall.createHttpRequests('get', this.someService.getsomeData, {}, {}).pipe(
map((result: Isomedatas) => {
if (result.body.statusCode === 200) {
} else {
}
}),
).subscribe();
//This method should call after the above api completion
this.getDriverDetails();
}
最佳答案
为此,您可以使用 rxjs
中的 combineLatest
函数。
使用下面的代码。
public createHttpRequests(
method: string,
url: string,
payload? : any,
params? : any,
): Observable<any> {
switch ((method).toLowerCase()) {
case 'get':
return this.createHttpGet(url, params);
case 'post':
return this.createHttpPost(url, payload);
default:
return this.http.get('');
}
}
// And my service call is below:
public ngOnInit(): void {
const userList$ = this.serviceCall.createHttpRequests('get', this.someService.getUserList, {}, {}).pipe(
map((result: Iuserlist) => {
if (result.body.statusCode === 200) {
} else {
}
}),
);
const someData$ = this.serviceCall.createHttpRequests('get', this.someService.getsomeData, {}, {}).pipe(
map((result: Isomedatas) => {
if (result.body.statusCode === 200) {
} else {
}
}),
);
combineLatest([userList$, someData$]).subscribe(([userList, someData]) => {
console.log(userList);
console.log(userList);
this.getDriverDetails();
});
}
关于angular - 在 Angular 9 中使可观察的调用同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63328919/