类型'标题'没有与'RequestOptionsArgs'类型相同的属性?

msa*_*ord 19 typescript angular

我刚刚对Angular 4应用程序和构建工具进行了两次重要的升级:

  1. @ angular/core ^4.1.3 => ^4.2.4(和/ http,/ forms等)
  2. tslint ^5.3.2 =>^5.4.3

我有一个服务,声明这样的选项:

@Injectable()
export class WorkOrderService {

    private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
    private options: RequestOptions = new RequestOptions(this.headers);

    constructor(private http: Http) {}

    /* Methods ... */
}
Run Code Online (Sandbox Code Playgroud)

以上现在不再验证tslint,抛出以下错误:

错误TS2559:类型'标题'没有与'RequestOptionsArgs'类型相同的属性.

源(@角/ HTTP interface.d.ts:43)清楚地允许Headers作为RequestOptionsArgs:

/**
 * Interface for options to construct a RequestOptions, based on
 * [RequestInit](https://fetch.spec.whatwg.org/#requestinit) from the Fetch spec.
 *
 * @experimental
 */
export interface RequestOptionsArgs {
    url?: string | null;
    method?: string | RequestMethod | null;
    /** @deprecated from 4.0.0. Use params instead. */
    search?: string | URLSearchParams | {
        [key: string]: any | any[];
    } | null;
    params?: string | URLSearchParams | {
        [key: string]: any | any[];
    } | null;
    headers?: Headers | null;
    body?: any;
    withCredentials?: boolean | null;
    responseType?: ResponseContentType | null;
}
Run Code Online (Sandbox Code Playgroud)

msa*_*ord 31

4.3的更新 HttpClient

HttpClient在角度4.3中引入的兼容的新语法是:

import { HttpClient, HttpHeaders } from "@angular/common/http";

private _options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
Run Code Online (Sandbox Code Playgroud)

不再RequestOptions:使用新的不可变HttpParamsMap 添加参数.

预4.3/Http

只是注意到RequestOptions现在要求你明确地将命名选项作为对象传递,如:

headers: Headers = new Headers({ 'Content-Type': 'application/json' });
options: RequestOptions = new RequestOptions({ headers: this.headers });
Run Code Online (Sandbox Code Playgroud)

  • 由于*this.*:`类型'{this:any; }'不能分配给'RequestOptionsArgs'类型的参数.对象文字可能只指定已知属性,'this'在类型'RequestOptionsArgs'中不存在.但我也希望如此. (2认同)
  • 非常感谢@msanford,但我收到此错误类型'{headers:HttpHeaders; }'不能分配给'RequestOptionsArgs'类型的参数.属性"标题"的类型不兼容.类型'HttpHeaders'不能指定为'标题'类型.'HttpHeaders'类型中缺少属性'forEach'.,当我这样请求----> this.http.post('http:// localhost:56451/map',{"username":username,"password":password},this._options) (2认同)