在Angular中,你可以使用RequestOptions
来设置fetch请求的credentials
选项。以下是一个示例:
import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DataService {
constructor(private http: Http) { }
fetchData(): Observable {
const url = 'https://api.example.com/data';
const withCredentials = true; // 根据条件设置是否携带凭据
// 创建一个 RequestOptions 对象
const requestOptions = new RequestOptions();
// 设置 'withCredentials' 选项
requestOptions.withCredentials = withCredentials;
// 发起请求
return this.http.get(url, requestOptions)
.map(response => response.json())
.catch(error => Observable.throw(error));
}
}
在上面的代码中,我们使用RequestOptions
类来设置fetch请求的选项。首先,我们创建了一个RequestOptions
对象,并设置了withCredentials
选项为一个布尔值。根据你的条件,你可以将withCredentials
设置为true
或false
。
然后,我们使用http.get()
方法发起了一个GET请求,并传入了我们创建的requestOptions
对象。最后,我们使用.map()
操作符将响应转换为JSON,并使用.catch()
操作符捕获任何错误。
这样,根据条件设置了fetch请求中的credentials
选项。