Home > Software engineering >  Redirect based on the return of an http request Angular
Redirect based on the return of an http request Angular

Time:10-16

I try to make a redirection when the user enters the 2FA code a request is sent to my API Rest to check if the code is valid, a Promise is sent back, at the first call of this request its value is undefined even if the token is sent by the user, at the second call the value becomes the expected one depending on the code entered by the user.

I tried several ways, in the component.ts by subscribing the request and retrieving the value but no success

    previousUrl!: string;
    isValid!: boolean;
    onSubmit() {
        this.tfaServices.verifyAuth(this.token).subscribe(v => this.isValid = v);
        // isValid = undefined in first call
        if (this.isValid)
            this.router.navigateByUrl(this.previousUrl);

But also in the html by directly subscribing the observable

// Need to click twice on the button to get redirect
    <button  (click)="onSubmit()" [ngClass]="btnStatus" [routerLink]="[(isValid$ | async) ? '../view' : []]">{{ this.inputDigitLeft }}</button>

But nothing changes, my value is always undefined and forces the user to click twice for the code to be taken into consideration

Environment Angular NestJS Docker

CodePudding user response:

You need to check the value inside the promise like so:

onSubmit() {
    this.tfaServices.verifyAuth(this.token).subscribe(v => {
      this.isValid = v;
      if (v) {
        this.router.navigateByUrl(this.previousUrl);
      }
    });
}
  • Related