I am using observable for HTTP request I want to make it as a synchronous call since am new to rxjs. And below code am using to doing the multiple calls, so after the completion of all the calls only I have to call the drive method. I referred a lot of links but I could not understand pls help me.
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('');
}
}
And my service call is below:
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();
}
For this purpose you can use combineLatest function from rxjs.
Use below code.
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();
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With