2016-06-07 91 views
1

我發現了一些與此有關的內容,但大多數示例和解釋已過時,並且不適用於RC1。Angular 2 - http get with Credentials

import {Injectable} from "@angular/core"; 
import {Http, HTTP_PROVIDERS, Response, RequestOptions, URLSearchParams} from "@angular/http"; 
import 'rxjs/add/operator/map'; 
@Injectable() 
export class AuthService { 
constructor(private _http: Http) {} 
GetLoggedUser(){ 
    return this._http.get('http://dev/api/v1/current-user') 
    .map((res:Response) => res.json()) 
} 
} 

我需要撥打這個電話正是因爲這遺留代碼:

$(document).ready(function() { 
        jQuery.ajax({ 
         type: 'GET', 
         url: 'http://dev/api/v1/current-user', 
         xhrFields: { 
          withCredentials: true 
         }, 
        }).done(function(data) { 
         $('#user').html(JSON.stringify(data)); 
        }); 
       }); 

所以,基本上我需要使用withCredentials呼叫。任何幫助?

回答

0

隨着RC1你需要擴展BrowserXhr類:

@Injectable() 
export class CustomBrowserXhr extends BrowserXhr { 
    constructor() {} 
    build(): any { 
    let xhr = super.build(); 
    xhr.withCredentials = true; 
    return <any>(xhr); 
    } 
} 

,並覆蓋BrowserXhr提供商與擴展:

bootstrap(AppComponent, [ 
    HTTP_PROVIDERS, 
    provide(BrowserXhr, { useClass: CustomBrowserXhr }) 
]); 

隨着即將到來的RC2,你就可以使用請求選項中的withCredentials屬性。

請參見以下鏈接瞭解詳情:

+0

RC2?有沒有RC2?很高興知道 !!!讓我先試着用你寫的RC1方式...... BRB –

+0

即將發佈的RC2 ;-)它還沒有發佈...... –

+0

哦,好的! btw..Thierry,包含「@injectable,export class CustomBrowserXhr」的塊必須與我編寫我的代碼的服務相同?或者可能是一個新文件?或者可能在我的main.ts?對不起,我很難實現這一個。 –