将选项参数传递给httpClient.post方法并不总是可以编译

时间:2018-08-25 08:29:47

标签: angular

为什么不能将options参数传递给httpClient.post<T>方法调用?

当我取消注释第二条返回行时,以下代码无法编译:

@Injectable()
export class CustomHttpService {

    constructor(private httpClient: HttpClient) { }

    public postWithHeaders<T>(url: string, body: string, headers?: HttpHeaders | null): Observable<T> {
        const options = {
            headers: this.prepareHeader(headers),
            observe: 'response' as 'body', // Have the response headers included in the response object
            responseType: 'json'
        };
        return this.httpClient.post<T>(url, body, this.prepareHeader(headers));
        // return this.httpClient.post<T>(url, body, options); why I cannot have this line instead of the above one ?
    }

    private prepareHeader(headers: HttpHeaders | null): object {
        headers = headers || new HttpHeaders();
        headers = headers.set('Content-Type', 'application/json');
        headers = headers.set('Accept', 'application/json');
        return headers;
    }

}

当我可以在另一个类中包含以下可以很好地编译的源代码时,这更加令人困惑:

  public login(username: string, password: string): Observable<any> {
    console.log('Sending the login credentials to obtain a token');
    const credentials = { 'email' : username, 'password' : password };
    // Have the response headers included in the response object
    const options = {
      observe: 'response' as 'body'
    };
    const url: string = environment.USER_REST_URL + '/login';
    return this.httpClient.post<any>(url, credentials, options);
  }

vscode IDE显示以下编译问题:

[ts]
L'argument de type '{ headers: object; observe: "body"; responseType: string; }' n'est pas attribuable au paramètre de type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Les types de la propriété 'headers' sont incompatibles.
    Impossible d'assigner le type 'object' au type 'HttpHeaders | { [header: string]: string | string[]; }'.
      Impossible d'assigner le type 'object' au type '{ [header: string]: string | string[]; }'.
        Signature d'index manquante dans le type '{}'.
const options: {
    headers: object;
    observe: "body";
    responseType: string;
}

控制台显示以下问题:

ERROR in src/app/core/service/custom-http.service.ts(17,51): error TS2345: Argument of type '{ headers: object; observe: "body"; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
  Types of property 'headers' are incompatible.
    Type 'object' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
      Type 'object' is not assignable to type '{ [header: string]: string | string[]; }'.
        Index signature is missing in type '{}'.

该问题与标题无关。即使从选项对象中删除headers属性,问题仍然相同。

更新:该问题确实与headers属性有关。将prepareHeader方法的返回类型设置为HttpHeaders可以解决此问题。为什么在我无法解释之前,IDE却没有反映出这一点。

我在Angular 6.0.4下。

2 个答案:

答案 0 :(得分:2)

问题在于,prepareHeader()的返回类型为object。将其更改为HttpHeaders。这就是编译器抛出错误的原因。

  

类型'object'不能分配给类型'HttpHeaders | {[标头:   字符串]:字符串|串[]; }'。

将返回类型修改为HttpHeaders

private prepareHeader(headers: HttpHeaders | null): HttpHeaders {
        headers = headers || new HttpHeaders();
        headers = headers.set('Content-Type', 'application/json');
        headers = headers.set('Accept', 'application/json');
        return headers;
}

还如下修改observeresponseType属性。

const options = {
            headers: this.prepareHeader(headers),
            observe: 'response' as 'body', // Have the response headers included in the response object
            responseType: 'json' as 'json'
};

有一个与observeresponseType属性相关的开放issue

答案 1 :(得分:-1)

使用HttpHeaders代替this.prepareHeader(headers)

import { HttpHeaders } from '@angular/common/http';

        const options = {
            headers:  new HttpHeaders(
                         { 'Content-Type': 'application/json' },
)}