Angular 2 - http get withCredentials

雨燕双飞 提交于 2019-12-20 05:27:09

问题


I found something regarding this, but most examples and explanations are deprecated and it's not applicable to RC1.

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())
} 
} 

I need to make this call exactly as this legacy code:

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

So, basically I need to make the call using withCredentials. Any help ?


回答1:


With RC1 you need to extend the BrowserXhr class:

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

and override the BrowserXhr provider with the extended:

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

With the upcoming RC2, you'll be able to use a withCredentials attribute in request options.

See these links for more details:

  • http://5thingsangular.github.io/2016/05/30/issue-6.html
  • https://github.com/angular/angular/pull/7281


来源:https://stackoverflow.com/questions/37681807/angular-2-http-get-withcredentials

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!