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

时间:2018-01-22 09:07:39

标签: angular angular-httpclient

我目前有以下服务:

@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...");
      }
    );

  }
}

在运行时,帖子如果成功,则返回以下对象:

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

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

如上所述,如何使用此键和值并使用它们?

2 个答案:

答案 0 :(得分:1)

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...");
  }
);

答案 1 :(得分:0)

你应该先把它转换成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...");
  }
);