简体   繁体   中英

How can i set login Response detail in Angular API Request?

I am connecting to my backend login service using Angular. But I can't set the popup message when the username or password is wrong. In case of any mistake, I want to show the detail message from the API on my page in the login process, but it does not show anything.

login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {



  form = new FormGroup({
    username: new FormControl(null, Validators.required),
    password: new FormControl(null, Validators.required),
  });
  constructor(private authService: AuthService ,private router: Router) {}

  loading = false;
  loginText = "Giriş Yap";
  testVar = undefined;

  submitForm() {
    if(this.form.invalid) {

      return;
    }
    this.loginText = "Checking.."
    this.loading = true;
    let username = String(this.form.get('username')?.value)
    let password = String(this.form.get('password')?.value)



    this.authService
      .login(username , password)
      .subscribe((_response) => {

        this.router.navigate(['/dashboard'])
      })

  }

  ngOnInit(): void {
  }

}

auth.service.ts

import { NONE_TYPE } from '@angular/compiler';
import { Injectable } from '@angular/core';
import { BehaviorSubject, tap } from 'rxjs';
import { ChockService } from './chock.service';
import { UsersModel } from './models/users.model';
import { LoginDetailModel } from './models/logindetail.model';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private _isLoggedIn$ = new BehaviorSubject<boolean>(false);
  private readonly TOKEN_NAME = 'access_token';
  isLoggedIn$ = this._isLoggedIn$.asObservable();
  user : UsersModel | null;
  errorMsg = "";



  get token() : any{
    return localStorage.getItem(this.TOKEN_NAME);
  }


  constructor(private chockService : ChockService) {

    this._isLoggedIn$.next(!!this.token);
    this.user = this.getUser(this.token);

   }

   login(username: string, password: string) {

    return this.chockService.login(username,password).pipe(
      tap((response :any) => {
        console.log(response)
        this._isLoggedIn$.next(true);
        localStorage.setItem(this.TOKEN_NAME, response.access_token);

      })
    )
   }

   private getUser(access_token: string): UsersModel | null{

    if(!access_token){
      return null;
    }
    console.log(JSON.parse(atob(access_token.split('.')[1])) as UsersModel);
    return JSON.parse(atob(access_token.split('.')[1])) as UsersModel;

   }
}

When the login process is successful, the response I get from the API is as follows, I can set it and use it. There is no problem.

{
"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFscCIsImlkIjoxLCJvd25lcm5hbWUiOiJiZXRveCIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTY2OTg2NTcyNn0.3uEKgA8Iqv5OGk5lyAXtPBot3e7SAfEQfNYf-aMBToI",
"token_type":"bearer"
}

When the login process is unsuccessful, I cannot set and export the response I received from the API to HTML so that I can show it on the page. Response from API when it fails:

{"detail":"Wrong password"}

I tried a code like this in the login.component.ts file, but the detail is never printed and set to the console. I put an if condition so that it doesn't redirect to the dashboard when login fails. What I want to do exactly is to be able to transfer the "detail" value from the response to the page if the login process is successful, if it is not successful, to redirect to the dashboard. Where do you think I might be going wrong?

this.authService
  .login(username , password)
  .subscribe((_response) => {
    if(_response.access_token in response) {
        this.router.navigate(['/dashboard'])
    }
    else {
        this.errMsg = _response.detail;
    }
    
  })

If your backend service meet the standard it'll return as an error response with Http header 401, then you need to catchError an error from your request.

import {catchError} from 'rxjs/operators';

...

  this.authService
  .login(username , password)
  .pipe(catchError((error) => { /* do something */}))
  .subscribe((_response) => {
      this.router.navigate(['/dashboard'])
  })

I solved problem like this in Angular 15

this.authService
      .login(username , password)

      .subscribe((_response) => {

        this.router.navigate(['/dashboard'])
      }, (err) => {
        this.errMsg = err.detail;
        console.log(err.error.detail);
        this.loading=false;
        this.loginText ="Giriş Yap";
        this.router.navigate(['/login'])
      })


  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM