使用 jwt 使用 laravel 和 angular 登录

Login using laravel and angular using jwt

我正在使用 angular 和 Laravel 进行用户身份验证,然后 link :

https://www.positronx.io/laravel-jwt-authentication-tutorial-user-login-signup-api/ https://www.positronx.io/laravel-angular-token-based-authentication-with-jwt/

身份验证有效,这是登录功能:

onSubmit() {
    this.authService.signin(this.loginForm.value).subscribe(
      (result: any) => {  
          this.responseHandler(result);
      },
      error => {     
        this.errors = error.error;
          if(this.errors.error_message)
          {
            this.toastr.error('', this.errors.error_message);
          }
        // }
      },() => {  
        this.authState.setAuthState(true);
        this.loginForm.reset()
        this.router.navigate(['user/dashboard']);
        this.toastr.success('Success', 'Logged In Successfully');
      }
    );
}

  // Handle response
  responseHandler(data :any ){  
    this.token.handleData(data.access_token);
  }
}

问题是当从服务器返回 401 时它也在执行这个成功块:

            this.authState.setAuthState(true);
            this.loginForm.reset()
            this.router.navigate(['user/dashboard']);
            this.toastr.success('Success', 'Logged In Successfully');

在 laravel 我返回 401 :

  if (! $token = auth()->attempt($validator->validated())) {  
            return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
        }

那不是成功块。订阅有 3 个参数。

1.Next

2.Error

3.Complete

无论您的 observable 发生什么(成功或错误),如果您编写了一个完整的方法,它总是会被调用。所以为了防止这种情况,将这 4 行放在 Next 方法中

this.authService.signin(this.loginForm.value).subscribe(
    (result: any) => {
      this.responseHandler(result);
      this.authState.setAuthState(true);
      this.loginForm.reset()
      this.toastr.success('Success', 'Logged In Successfully');
      this.router.navigate(['user/dashboard']);
    },
    error => {
      this.errors = error.error;
      if(this.errors.error_message){
          this.toastr.error('', this.errors.error_message);
      }
 });