0

I have a problem while refreshing my page

I have a service that runs the following code:

service.ts

public goToCommit(value: boolean) {
    if (this.accountServ.isAutho() || this.person.getNb() % 48 === 0) {
        this.personService.savePerson(this.person).subscribe(() => {
          this.person= null;
        });
      } else {
        throw new Error('Account not authorized to goToCommit');
      }
  }

(this treatment is long, this method is used in other places )

in my component I have this:

component.ts

this.service.goToCommit(value);
this.router.navigate (['/persons']);

The problem is that I am redirected to /persons before the processing ends.

How can I wait for the goToCommit method to finish and redirect after ?

Thank you

Nitneuq
  • 99
  • 3
  • 12
  • `How can I wait for the goToCommit method to finish and redirect after ?` ← Return an observable from the method and subscribe to it in your component. In your service method you can use `tab` (`.pipe(tap(() => this.person = null))` to still set the value of `this.person`. – Igor May 04 '20 at 15:24
  • return new Observable(); like this ? – Nitneuq May 04 '20 at 15:27
  • No, return the observable. `if(conditionHere) { return this.personService.savePerson(this.person).pipe(tap(() => this.person = null)); } else { throw new....};` – Igor May 04 '20 at 15:28
  • this error is generated `Type 'Subscription' is missing the following properties from type 'Observable': _isScalar, source, operator, lift, and 6 more.ts(2740) ` – Nitneuq May 04 '20 at 15:36
  • So the service returns the observable, the component subscribes to that observable. `this.service.goToCommit(value).subscribe(() => this.router.navigate (['/persons']););` – Igor May 04 '20 at 15:43
  • i can't subscribe in the component .. just unsubscribe.. – Nitneuq May 04 '20 at 15:59
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213098/discussion-between-nitneuq-and-igor). – Nitneuq May 04 '20 at 15:59

0 Answers0