2016-07-04 27 views
1

我使用JWT進行授權。在AngularJS 1.x中我用下面的函數來登錄:

function login(username, password) { 
     var deferred = $q.defer(); 

     $http.post("/api/login", { 
      "username": username, 
      "password": password 
     }).then(function(response) { 
      if (response.data && response.data.token) { 
       var tokenBegin = response.data.token.substring(0,6); 
       var bearer = (tokenBegin === 'Bearer') ? '' : 'Bearer '; 
       $http.defaults.headers.common.Authorization = bearer + response.data.token; 
       deferred.resolve({ status: true, message: 'Login complete' }); 
      } else { 
       deferred.reject(response); 
      } 
     }, function(reason) { 
      deferred.reject(reason) 
     }); 

     return deferred.promise; 
    } 

被修改$http.defaults對象。由於Http類似乎沒有defaults對象,所以我在Angular2和TypeScript中有點失落。我會怎麼做?

回答

3

有幾種方法可以做到這一點:

  • 您可以實現自己的BaseRequestOptions類:

    import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from '@angular/http'; 
    
    export class AppRequestOptions extends BaseRequestOptions { 
        constructor() { 
        } 
    
        merge(options?:RequestOptionsArgs):RequestOptions { 
        options.url = 'https://www.test.org' + options.url; 
        return super.merge(options); 
        } 
    } 
    

    ,我註冊這樣說:

    bootstrap(App, [ 
        HTTP_PROVIDERS, 
        provide(RequestOptions, {useClass: AppRequestOptions}) 
    ]); 
    
  • 擴展Http(或XHRBackend)類本身:

    @Injectable() 
    export class CustomHttp extends Http { 
        constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) { 
        super(backend, defaultOptions); 
        } 
    
        request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> { 
        console.log('request...'); 
        return super.request(url, options).catch(res => { 
         // do something 
        });   
        } 
    
        get(url: string, options?: RequestOptionsArgs): Observable<Response> { 
        console.log('get...'); 
        return super.get(url, options).catch(res => { 
         // do something 
        }); 
        } 
    } 
    

    和如下所述註冊它:

    bootstrap(AppComponent, [HTTP_PROVIDERS, 
        new Provider(Http, { 
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions), 
        deps: [XHRBackend, RequestOptions] 
        }) 
    ]); 
    

參見這些問題:

+0

我認爲是這樣的:merge(options?:RequestOptionsArgs):RequestOptions options.headers.Authorization ='Bearer:sometoken'; return super.merge(options); }' – stwissel