代码之家  ›  专栏  ›  技术社区  ›  DESH

如何在Angular 5中使用返回值/秒?

  •  0
  • DESH  · 技术社区  · 7 年前

    我目前有以下服务:

    @Injectable()
    export class UserServiceService {
      userEmail: string;
      userPassword: string;
    
      constructor( private http: HttpClient ) { }
    
      login( userEmail, userPassword ){
        let body = { "email": userEmail, "password": userPassword};
    
        this.http.post('/customer/service/logging', body, httpOptions).subscribe(
          data => {
            console.log( data );
          },
          error => {
            console.error("There Is Something Wrong\nPlease Try Again Later...");
          }
        );
    
      }
    }
    

    在运行时,如果成功,post将返回以下对象:

    {message: "Login Successful", status: "success"}
    

    我想做的是获取密钥状态并将其用于路由(如果需要) 成功),然后是提示用户登录的关键消息 成功/未成功。

    如上所述,我如何获取这些键和值并使用它们?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Elmer Dantas    7 年前
    this.http.post('/customer/service/logging', body, httpOptions).subscribe(
      data => {
        if(data.status === 'success'){
            alert(data.message); //or do whatever you want 
         }else {
         alert('login fails'); // or alert(data.message) with the error message from the server
        }
      },
      error => {
        console.error("There Is Something Wrong\nPlease Try Again Later...");
      }
    );
    
        2
  •  0
  •   Khaled Ahmed    7 年前

    您应该首先将其转换为json

    this.http.post('/customer/service/logging', body, httpOptions)
    .subscribe(
      data => {
        let res = data.json();
        console.log( res.status);
    
      },
      error => {
        console.error("There Is Something Wrong\nPlease Try Again Later...");
      }
    );