1

new here so apologies if I don't lay this out as you'd expect.

So I'm submitting my reactive form data to the server (mongodb database). I then want to route to a new path passing the ID element that the database returns to the front end as a param in the URL.

This is what I have in the submit function so far:

  onsubmit(){
    let opdata = null;
    this.location.saveOpnote(this.form.value)
    .subscribe(response => {
      opdata = response
      console.log(response)
    })
    this.route.navigate(['/opnotes/mopsdisplay', opdata._id])

  }

So data saves perfectly and backend returns the _id of the new entry. Browser complains:

ERROR TypeError: Cannot read property '_id' of null

My understanding is the browser is looking at this before the asynchronous part of saving to the server is completed and the _id is available.

How do I get round this?

Many thanks.

  • There is no way around this. Asynchronous must be asynchronous all the way down. If your subscription library has a way to convert to a `Promise`, use that and then either `await` it or call `.then()` on the `Promise` returned. You tagged [tag:angular] so maybe take a look at this answer: [Subscription to promise](https://stackoverflow.com/q/55599421/691711). Essentially, you want `subscription -> promise -> .then() -> navigation`. – zero298 Jun 24 '20 at 14:26
  • Also relevant: [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/691711) – zero298 Jun 24 '20 at 14:35
  • Is there a reason that the navigation function is not inside the response handling? – DanGo Jun 24 '20 at 14:36

2 Answers2

1

You want your request to be completed, therefore navigation part should be the last line inside the subscription not outside of it. As your call on save is asynchronous as you mentioned, navigation block gets executed before the save operation finishes.

Berk Kurkcuoglu
  • 1,453
  • 1
  • 9
  • 11
0

You can create a new function navigateToMopsDisplay just to navigate to your desired route. Once the Opnotes is saved, the opdata response can be sent to navigateToMopsDisplay with opdata._id and can be navigated

navigateToMopsDisplay(id) {
  this.route.navigate(["/opnotes/mopsdisplay", id]);
}


onsubmit() {
  this.location.saveOpnote(this.form.value).subscribe(response => {
    const opdata = response;
    this.navigateToMopsDisplay(opdata._id);
  });
}
bharat1226
  • 159
  • 9