您需要扩展默认的 Http 服务并将 withCredentials 设置为 true
http.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, Request, RequestOptions, Response, XHRBackend } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class HttpService extends Http {
constructor(backend: XHRBackend, options: RequestOptions) {
super(backend, options);
}
request(url: string | Request, options?: any): Observable<Response> {
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
options.withCredentials = true;
} else {
url.withCredentials = true;
}
return super.request(url, options);
}
}
http.service.factory.ts
import { RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './http.service';
export function HttpServiceFactory(backend: XHRBackend, defaultOptions: RequestOptions) {
return new HttpService(backend, defaultOptions);
};
在你的模块文件中你需要替换你的http服务
import { HttpServiceFactory } from './http.service.factory';
import { Http, RequestOptions, XHRBackend } from '@angular/http';
...
providers: [
{
provide: Http,
useFactory: HttpServiceFactory,
deps: [XHRBackend, RequestOptions]
}
]