0

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.

6
  • 1
    where are you trying to access it? What does "Leave ngonit" mean? Commented Jun 16, 2019 at 10:23
  • I want use my invoiceItems array in HTML file and display all of these items. In ngOnInit method after push data into invoiceItems array it is not empty, everywhere else array is empty Commented Jun 16, 2019 at 10:27
  • 1
    There is too little information to reproduce. You should post your HTML structure and the relation between the two components. One possible solution could be to use a BehaviorSubject instead of a Subject inside your service Commented Jun 16, 2019 at 10:37
  • Do you have multiple instances of your Service class? How are you injecting them? Commented Jun 16, 2019 at 10:37
  • @PierreDuc I used BehaviorSubject and now it is working properly, data is displaying I also changed way to initialize invoiceItems to this.invoiceItems = data.invoice; Commented Jun 16, 2019 at 10:50

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.