当选项作为变量而不是文字传递时,http.post不会编译

时间:2018-05-02 05:17:04

标签: angular5

我注意到以下代码没有编译(选项作为变量传递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'
})

为什么?

1 个答案:

答案 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'
};