简体   繁体   English

当Api返回响应时,如何以角度显示“登录失败。请重试”消息?

[英]How to show “Login In failed.Please try again” message in angular when Api returns the response?

Actually i have simple login screen in angular as: 实际上我有一个简单的登录屏幕,角度如下:

在此处输入图片说明

When the username and password is entered,it successfully hit the /login url and if it is correct it goes to the userdashboard or admindashboard and when username and password is incorrect it shows me /403 fobidden page. 输入用户名和密码后,它会成功打入/ login网址,如果正确,它将转到用户仪表板或admindashboard;如果用户名和密码不正确,则会显示/ 403禁用页面。

The output in console comes like : 控制台中的输出如下: 在此处输入图片说明

Actually i want to show "Login Failed Please enter correct Username and Passowrd Message" but the api is returning the response in the form 实际上,我想显示“登录失败,请输入正确的用户名和Passowrd消息”,但api以以下形式返回响应:

@PostMapping(value="/login")
    public ResponseEntity<UserDTO> login(@RequestBody User user,HttpServletRequest request,HttpServletResponse response){
        try {
            Authentication authentication= authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()));
            final JwtUser userDetails=(JwtUser) authentication.getPrincipal();
            System.out.println(userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            final String token=jwtTokenUtil.generateToken(userDetails);
            response.setHeader("Token",token);
            return new ResponseEntity<UserDTO>(new UserDTO(userDetails.getUser(), token),HttpStatus.OK);
            }catch(Exception e) {
            throw new UnauthorizedExcpetion(e.getMessage());

        } 

If login is success it returns user object neither it returns the message "Bad Credintials". 如果登录成功,则不返回用户对象,也不返回消息“ Bad Credintials”。

And in my angular I have tried to check the error condition and want to apply the message strategy but it is not printing in console.log() if the login is failed but if the login is success then response is printed in console.log(). 在我的角度来看,我尝试检查错误情况并希望应用消息策略,但是如果登录失败,则不会在console.log()中打印,但是如果登录成功,则响应会在console.log()中打印)。

loginUser(user:any){
    this.userService.loginUser(user).subscribe((response) => {
      console.log("test");
        if(response){
        console.log(response.token);
            if(response.token){
                localStorage.setItem('currentUser',JSON.stringify(response));
                if(response.user.role==='ADMIN'){
                    this.router.navigate(['/admindashboard']);
                }else{
                    this.router.navigate(['/userdashboard']);
                }
            }
         else{
        console.log(response.error.message);
      }

        } 



    })

  }

userservice.ts userservice.ts

loginUser(user:any):Observable<any>{
         const headers=new HttpHeaders({'Access-Control-Allow-Origin':'*'});
         return this.http.post("http://localhost:8080/login",user,{headers:headers});
   } 

The response that ur getting goes into the error block in the front end so declare a boolean varaible as showErrormessage as false and write the following code in html 我们得到的响应进入前端的错误块,因此将布尔变量声明为showErrormessage为false并在html中编写以下代码

  <div *ngIf="showErrorMessage">
    <h1>Invalid username and password Please try again</h1>
  </div>

And in ts file write this 并在ts文件中写这个

//Declare this variable showErrorMessage=false; //声明此变量showErrorMessage = false;

loginUser(user:any){
  showErrorMessage = false;
  this.userService.loginUser(user).subscribe(
      (response) => {

      console.log("test");
          if (response) {
              console.log(response.token);
          if (response.token) {
              localStorage.setItem('currentUser', JSON.stringify(response));
          if (response.user.role === 'ADMIN') {
              this.router.navigate(['/admindashboard']);
      }   else {
              this.router.navigate(['/userdashboard']);
      }
    } else {
      console.log("No Token");
    }
  }
},
(error) => {
  showErrorMessage = true;
}

) } )}

You need to catch the error of the observable. 您需要捕获可观察的错误。 Observe takes up to 3 functions, the first handles good data, the second handles errors and the third is a final call eg 观察最多需要3个功能,第一个处理好数据,第二个处理错误,第三个是最终调用,例如

let subscription = this.data.subscribe(
          (value) => { /* Do something with value */ },
          (error) => { /* Do something with error */ },
          () => { /* Do something with done*/ }
      );

So you need to add an error handler to catch the condition you are talking about. 因此,您需要添加一个错误处理程序以捕获您正在谈论的情况。

Reference: https://angular.io/guide/observables 参考: https//angular.io/guide/observables

In this case, you will get your response in the error function of observable. 在这种情况下,您将在observable的误差函数中得到响应。 So, just catch the error. 因此,仅捕获错误。

Here I have updated the code. 在这里,我更新了代码。

loginUser(user:any){
    this.userService.loginUser(user).subscribe((response) => {
      console.log("test");
        if(response){
        console.log(response.token);
            if(response.token){
                localStorage.setItem('currentUser',JSON.stringify(response));
                if(response.user.role==='ADMIN'){
                    this.router.navigate(['/admindashboard']);
                }else{
                    this.router.navigate(['/userdashboard']);
                }
            }
         else{
        console.log(response.error.message);
      }   
        }            
    }, (error) => {
        console.log('Login Failed'); // handle login failed here. 
    })

  }

Pass a second function in subscribe to catch the error. 在订阅中传递第二个函数来捕获错误。

  loginUser(user:any){
    this.userService.loginUser(user).subscribe(
      (response) => {
      console.log("test");
        if(response){
        console.log(response.token);
            if(response.token){
                localStorage.setItem('currentUser',JSON.stringify(response));
                if(response.user.role==='ADMIN'){
                    this.router.navigate(['/admindashboard']);
                }else{
                    this.router.navigate(['/userdashboard']);
                }
            }else{
              console.log("No Token");
            }
        } 
      },
      (error)=>{
        console.log(error.message);
      }
    )
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何显示html中的“登录失败”消息,具体取决于servlet响应 - how to show a “login failed” message in html, depending on servlet response 登录失败。请检查您的网络连接,然后重试 - Failed to sign in. Please check your network connection and try again Android Facebook API错误:出了点问题,请重试 - Android Facebook API error: something went wrong please try again Google Play服务“无法登录。请检查您的网络连接,然后重试” - Google Play Services “Failed to sign in. Please check your network connection and try again” 如何从Excel第一行进行迭代并尝试登录,然后再次迭代至第二行并尝试使用带有POI的Selenium再次登录? - How to iterate from first row of excel and try to login and then again iterate to second row and try to login again using Selenium with POI? 输入一个数字,不是数字,请重试 - Enter a number, That was not a number, please try again 当 API 响应返回 Java 中的 null 正文时如何处理? - How to handle case when API response returns a null body in Java? 如果登录失败,如何在登录页面中显示消息 - How to show a message in the login page if the login fails Selenium Webdriver-Java,浏览器显示消息“错误:此页面已过期。 请取消此操作,然后重试”。 - Selenium Webdriver - Java, Browser shows message “ERROR: This page has expired. Please cancel this operation and try again” on button click 在测试Web API响应时间时得到401,请协助 - getting 401 when testing web api response time please assist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM