Reputation: 55
I'm trying to communicate between my 2 components. In first component I have list with items and I want to send one of this item to my second component to edit them. In first component I set data in my service and in second component I want read this data from service, data is coming but when I set this data to my array after leave ngOnInit method my array is clear.
It is my onClick for edit button in first component
editPurchasesInvoice(i : number) {
this.purchasesService.editPurchasesInvoice(this.purchasesInvoices[i].gpInvoiceitemsByGpInvoiceRecid);
this.router.navigate(['new'], {relativeTo: this.route});
}
Service methods
subject = new Subject<any>();
editPurchasesInvoice(invoiceItems: GpInvoiceitem[]) {
this.subject.next({invoice: invoiceItems});
}
getEditedInvoice(): Observable<any> {
return this.subject.asObservable();
}
it is my scond component
ngOnInit() {
this.subscription = this.purchaseService.getEditedInvoice().subscribe( data => {
this.invoiceItems.push(data.invoice);
});
}
After leave ngOnInit method data is lost.
Upvotes: 0
Views: 78
Reputation: 71931
A subscription to a Subject
will only be received once new data is transmitted. A BehaviourSubject
will emit the last pushed data on subscription. You can also use a ReplaySubject
, which is basically the same, but where you can control the count of emits and you do not need to specify an initial value.
As stated in the comments, you should update your service to use either of these two, considering your data, I suggest a ReplaySubject
:
readonly subject = new ReplaySubject<any>(1)
editPurchasesInvoice(invoiceItems: GpInvoiceitem[]) {
this.subject.next({invoice: invoiceItems});
}
getEditedInvoice(): Observable<any> {
return this.subject.asObservable();
}
Upvotes: 1