【问题标题】:Type 'Headers' has no properties in common with type 'RequestOptionsArgs'?“Headers”类型与“RequestOptionsArgs”类型没有共同的属性?
【发布时间】:2017-11-27 11:12:40
【问题描述】:

我刚刚对我们的 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 ... */
}

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

错误 TS2559:“Headers”类型与“RequestOptionsArgs”类型没有共同的属性。

来源 (@angular/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;
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    更新 4.3 HttpClient

    Angular 4.3 中引入的与HttpClient 兼容的新语法是:

    import { HttpClient, HttpHeaders } from "@angular/common/http";
    
    private _options = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
    

    不再有RequestOptions:使用新的不可变HttpParams Map 添加参数。

    4.3 前/Http

    只是注意到RequestOptions 现在要求您将命名选项作为对象显式传递,例如:

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

    【讨论】:

    • 我遇到了类似的问题,感谢提供解决方案
    • @LLai 对象解构在这种情况下不起作用,因为 this.:Argument of type '{ this: any; }' is not assignable to parameter of type 'RequestOptionsArgs'. Object literal may only specify known properties, and 'this' does not exist in type 'RequestOptionsArgs'. 但我也希望如此。
    • @AkshayVijayJain 你在混合范式。 HttpClient 不是来自@angular/http,它来自@angular/common/http,其余部分也是从这里导出的。更新了帖子。
    • 非常感谢@msanford,但是我收到此错误 Argument of type '{ headers: HttpHeaders; }' 不可分配给“RequestOptionsArgs”类型的参数。属性“标题”的类型不兼容。类型“HttpHeaders”不可分配给类型“Headers”。 “HttpHeaders”类型中缺少属性“forEach”。 ,当我这样请求时---->this.http.post('localhost:56451/map', { "username": username, "password": password }, this._options)
    • @AkshayVijayJain 我很高兴。同样,您正在混合范式。我在帖子的 second 部分留下了RequestOptionsArgs,因为它不再适用于HttpClient。两个完整的代码部分是等价的。如果您有更复杂的情况(例如设置请求参数),我会发布一个新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 2022-08-10
    相关资源
    最近更新 更多