I am having a scenario where I need to call to the multiple HTTP requests but I am unable to synchronize it.
Below is the code for the same. I am unable to set the cartId
(commented down below) value from the HTTP service but I am able to get the response from the service(commented down below)
export class ShoppingCartService {
constructor(private http:HttpClient) { }
private create() {
return this.http.post('http://localhost:8090/shoppingcart',{});
}
private getCart(cartId:string):Observable <any>{
return this.http.get(`http://localhost:8090/shoppingcart/${cartId}`)
.pipe(map((response)=>{
return response;
}));
}
private getOrCreateCartId() {
let cartId = localStorage.getItem('cartId');
let id;
if (!cartId) {
this.create().toPromise().then(result => {
localStorage.setItem('cartId', result.body.id);
id = result.body.id;
});
return this.getCart(id);
} else
return this.getCart(cartId);
}
addToCart(product: Product) {
let cartId;
this.getOrCreateCartId().toPromise().then(response => {
console.log(response.body.id); //here i am able to print the response
cartId = response.body.id;
});
console.log(cartId); //here i am getting the cartId value as the
undefined..
}
}
Please help me to synchronize this I have tried many solutions but nothing is working.