2016-09-22 59 views
1

我有以下代碼來驗證使用Ionic 2,angularjs和devise_token_auth的用戶,但是如果成功登錄,我會在響應的頭部接收訪問令牌,而不是在json中。如何使用Angularjs訪問響應頭中的令牌?

authenticate(user) { 
     var creds = "email=" + user.name + "&password=" + user.password; 
     var headers = new Headers(); 
     headers.append('Content-Type', 'application/x-www-form-urlencoded'); 

     return new Promise(resolve => { 
      this.http.post('http://localhost:3000/auth/sign_in', creds, {headers: headers}).subscribe(data => { 
       if(data.json().data){ 
        this.storeUserCredentials("MY TOKEN IN THE HEADER"); 
        resolve(true); 
       } 
       else 
        resolve(false); 
      }); 
     }); 
    } 

但是我開始學習AngularJS和離子。我不知道要訪問標頭中的訪問令牌

+0

您是否嘗試訪問'response.access_token'?這對我有用。 –

回答

1

這就是我們如何從$ http響應中訪問響應標頭。

$http.post('/api').then(function(response) { 
    //Accessing header 
    console.log(response.headers()['access-token']); 
}); 

您的代碼有點不同。你可以試試這個。

this.http.post('http://localhost:3000/auth/sign_in', creds, {headers: headers}).subscribe(data => { 
      if(data.json().data){ 
       this.storeUserCredentials(data.json().headers()['access-token']); 
       resolve(true); 
      } 
      else 
       resolve(false); 
     });