代码之家  ›  专栏  ›  技术社区  ›  MPoutanen

角度6:返回HttpHeaders

  •  0
  • MPoutanen  · 技术社区  · 6 年前

    我目前正在构建一个用于学习的小角度应用程序。我打电话给a。net核心WebApi来获取/操作数据。

    现在,我的问题是:

    在所有Post和Put请求中,我使用的标题都完全相同:

    const headers = new HttpHeaders().set('content-type', 'application/json');
    

    我这样附加它(例如,在post中):

    return this.http.post<SmartCard>(AppDefinitions.ApiSmartCardAdminPath, body, { headers })
    

    由于post和put都有相同的标题,我考虑将其添加到我的AppDefinitions类中,如下所示:

    import { HttpHeaders } from "@angular/common/http";
    
    export class AppDefinitions {
        public static ApiBasePath: string = "http://<my webapp name>.azurewebsites.net/api/";
        public static ApiLoginPath: string = AppDefinitions.ApiBasePath + "Login/";
        public static ApiSmartCardAdminPath: string = AppDefinitions.ApiBasePath + "SmartCard/";
        public static JsonHttpHeaders: HttpHeaders = new HttpHeaders().set('content-type', 'application/json');
    }
    

    因此,我继续删除post-and-put方法中的ehader定义,并将其替换为对JsonHttpHeaders的调用,然后如下所示:

    return this.http.post<SmartCard>(AppDefinitions.ApiSmartCardAdminPath, body, { this.GetHttpHeaders() })
    

    但这只会导致一个错误,即:

    Argument of type '{ this: any; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
      Object literal may only specify known properties, and 'this' does not exist in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.
    

    现在,我不确定我是否正确理解了这一点,但这是否意味着我的AppDefinitions正在返回任何?我怎样才能改变这一点?我还尝试在服务类本身中创建以下方法:

      GetHttpHeaders() : HttpHeaders{
        const headers = new HttpHeaders().set('content-type', 'application/json');
        return headers;
      }
    

    但这会导致同样的错误。

    我做错了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ritwick Dey    6 年前

    设置标头属性。

    return this.http.post<SmartCard>(AppDefinitions.ApiSmartCardAdminPath, body, { headers: this.GetHttpHeaders() })