Reputation: 2116
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();
});
}
Upvotes: 0
Views: 48
Reputation: 31125
ReplaySubject
EventEmitter
is a an Angular specific extension of RxJS Subject
. 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 receive the emissions 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 => {
...
});
}
Given that your components are related through Angular Router, you could use routing parameters to send data b/n them. See here for more info.
Upvotes: 1