在GET之后POST并在Angular2上使用它

时间:2017-09-26 14:41:56

标签: angular angular2-services

我想创建一个执行GET和POST的服务,并在组件上使用它。最好的方法是什么?

auth.service.ts

getToken() {
    return this.http.get(this.getServerUrl() + '/token');
}

login(username: string, password: string) {
    return this.getToken()
    .subscrive((response: Response) => {
        return this.http.post(this.getServerUrl() + '/login'
            , JSON.stringify({username: username, password: passowrd}))
    });
 }

login.component.ts

login(username, password) {
    event.preventDefault();
    this.authService.login(username, password)
      .subscribe(
        response => {
            console.log("success");
        },
        error => {
            console.log(error.text());
        }
      );
  }

1 个答案:

答案 0 :(得分:0)

假设您需要此令牌一次,则承诺将返回一次,然后执行http post

this.getToken()
.then(response=>{
if(response){
this.http.post ....
}
});