我注意到以下代码没有编译(选项作为变量传递httpOptions
)
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true,
observe: 'response'
};
return this.http.post(this.SIGNIN_USER_URL, body, httpOptions); // options is passed as a variable `httpOptions`
我收到以下错误
Argument of type '{
headers: HttpHeaders;
observe: string;
responseType: string;
}' is not assignable to parameter of type'{
headers?: HttpHeaders;
observe?: "body";
params?: HttpParams; reportProgress?: boolean;
respons...'.
Types of property 'observe' are incompatible.
Type 'string' is not assignable to type '"body"'.'
但是下面的代码确实(选项作为文字对象传递)
return this.http.post(this.SIGNIN_USER_URL, body, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true,
observe: 'response'
})
为什么?
答案 0 :(得分:0)
如评论中所述,在没有帮助的情况下,TypeScript编译器将假定给定的字符串可以是任何字符串,因此将其类型推断为string
。
但HttpClient.post(...)
method's options
parameter限制性更强,只接受HttpObserve
属性的observe
类型(which only allows 'body' | 'events' | 'response'
)。
如果您使用类型断言来帮助编译器,您将解决您的问题:
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true,
observe: 'response' as 'response'
};