Hello I have a component that adds and item to cart, it calls a service addProductToCart. On post I do a subscribe to get the Id of that item that was added to the post which I will add more functionality later, I'm just doing a step at a time. I tested it and I do get the id of the item as well as adding to the cart, but I'm getting an error when I go to the development tool (Cannot read properties of undefined reading subscribe) even though I don't get any compile errors on VS code. I have added a code snippet of the component function it is complaining about. I have read a similar issue but I do return. Can some one tell me what I'm doing wrong, is it that I don't have any parameters in my subscribe? I'm not sure. Can some one point me in the right direction, your help would be greatly appreciated
Component productitem.ts
handleAddToCart(){
this.cartService.addProductToCart(this.productItem)
.subscribe(() =>{
this.msg.sendMsg(this.productItem)
})
}
cart service
addProductToCart(product:Product):Observable<any>{
alert("Inside add product to cart");
this.http.post<any>(cartUrl, {product}).subscribe(data =>{
alert("To this point");
this.postId=data.id;
console.log("Do I get Id from a post" this.postId)
})
return
}
CodePudding user response:
You shouldnt subscribe in your service. Something like that should be close to what you need.
addProductToCart(product:Product):Observable<any>{
return this.http.post<any>(cartUrl, {product}).pipe(
map(data => {
this.postId=data.id;
return data;
})
)
}
CodePudding user response:
you are not returning the observable
addProductToCart(product:Product):Observable<any>{
alert("Inside add product to cart");
return this.http.post<any>(cartUrl, product).pipe(
tap(data =>{
alert("To this point");
this.postId=data.id;
console.log("Do I get Id from a post" this.postId);
}));
}
instead of subscribing in you service. You can get the data with tap. It does not do anything to the data, it will just read it as it passes through.