I am trying to get a response from a subscription that I have. I can see that I get to the cart component fine but the subscription doesn't seem to be working and I don't see any errors either. Here is my code
Service
@Output() event = new EventEmitter();
Products component
addToCart(product): void {
this._productsService.event.emit(product);
}
goToCart(): void {
this.router.navigate(['cart']);
}
Cart component
ngOnInit(): void {
console.log("gets here");
this._productsService.event.subscribe(product => {
console.log(product);
let index = -1;
index = this.cartProducts.findIndex(
p => p.id === product.id
);
this.cartProducts.push(product);
this.sum();
});
}
CodePudding user response:
Option 1: ReplaySubject
EventEmitter
is a an Angular specific extension of RxJSSubject
. As such, I'd say better to use it in conjunction with@Output()
decorator b/n parent-child components as it is meant to be used.Subscriptions to RxJS
Subject
, which you're indirectly using here, would only emit the values after the subscription. In your case, the event is emitted before the subscription.Instead you could use RxJS
ReplaySubject
with buffer 1 that would the last emitted value to future subscribers.
Service
import { ReplaySubject } from 'rxjs';
private eventSource = new ReplaySubject(1);
public event$ = this.eventSource.asObservable();
public setEvent(value) {
this.eventSource.next(value);
}
Products component
addToCart(product): void {
this._productsService.setEvent(product);
}
goToCart(): void {
this.router.navigate(['cart']);
}
Cart component
ngOnInit(): void {
this._productsService.event$.subscribe(product => {
...
});
}
Option 2: Router params
Given that your components are related through Angular Router, you could routing parameters to send data b/n them. See here for more info.