在Http请求的options中添加withCredentials属性为true
代码示例:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private API_URL = 'https://example.com/api/';
constructor(private http: HttpClient) { }
callGetApi() {
const options = {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
withCredentials: true
};
return this.http.get(this.API_URL + 'getData', options);
}
callPostApi(data: any) {
const options = {
headers: new HttpHeaders().set('Content-Type', 'application/json'),
withCredentials: true
};
return this.http.post(this.API_URL + 'postData', data, options);
}
}