3

Basically I have a component with a list of elements and I have a detail component, where you can edit or add a new element.

After I add an element via a http service (this.myservice is based upon hero.service.ts from the documentation https://angular.io/docs/ts/latest/tutorial/toh-pt6.html) to my server. Then I directly jump back to the list of element component.

I use Zone, so that ngOnInit is called. Angular 2 ngOnInit not called

The problem is that quite often the list of elements is not updated with the new element yet. I suppose the order of the asynchronous HTTP requests get mixed up.

How would a good solution look like?

export class DetailElemComp {
    this.myService.addElem(this.elem)
      .subscribe(
        error => this.errorMessage = <any>error);
    this.zone.run(() => this.router.navigate(['ListComponent']));
}
export class ListOfElemComp {
    ngOnInit() {
        this.myService.getElems()
          .subscribe(
            elems => this.elems = elems,
            error => this.errorMessage = <any>error);
    }
}
Community
  • 1
  • 1
Johannes
  • 2,732
  • 5
  • 23
  • 32

1 Answers1

4

Well, like you said, it's an asynchronous request. So if you want to do something after the request has finished, I'd suggest moving that logic into the onCompleted callback lambda of the subscribe function like so:

export class DetailElemComp {
    this.myService.addElem(this.elem)
      .subscribe(
        data => null,
        error => this.errorMessage = <any>error,
        () => this.zone.run(() => this.router.navigate(['ListComponent']))
      );
}

Code below that subscribe call will otherwise run before the callbacks inside of the subscribe method do.

Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71