2017-09-26 10 views
0

我想創建一個GET和POST的服務並在組件上使用它。什麼是最好的方式來做到這一點?GET後POST並在Angular2上使用它

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()); 
     } 
    ); 
    } 
+0

您是否嘗試過使用承諾獲取令牌,然後在發佈後進行發佈 –

回答

0

假設你需要這個令牌一次,承諾將恢復它一次,然後進行http post

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