Angular 2 - http get with Credentials

Angular 2 - http get with Credentials

问题描述:

我发现了一些与此有关的内容,但大多数示例和解释已过时,并且不适用于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呼叫。任何帮助?

随着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?对不起,我很难实现这一个。 –