【问题标题】:Send headers through generic method on HTTP CRUD workflow通过 HTTP CRUD 工作流上的通用方法发送标头
【发布时间】:2019-07-25 00:30:06
【问题描述】:

我有这样的服务:

注意:这里我需要使用cookies

  book(data: Spa): Observable<any> {
    return this.http.post(`${environment.apiURL}:${environment.port}/${environment.domain}/abc/my.json`, data,
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });
  }

您可以看到我必须发送headers 的每个方法。这是非常丑陋的,而不是DRY。所以我想写通用的CRUD 来自动添加它。我该怎么做?

我试过这个:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { RequestOptions } from '@angular/http';

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor(private http: HttpClient) { }

  post(url, params): Observable<any> {
    return new Observable(observer => {
      const headers = new Headers();
      let options = new RequestOptions({ headers: this.createHeader(headers) });
      this.http.post(url, params, options)
        .subscribe(response => {
          observer.next(response);
          observer.complete();
        }, (e) => {
          observer.error(e);
        });

    })
  }

  createHeader(headers: Headers): Headers {
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return headers;
  }
}

但它在这一行上给出了这个compile time 错误let options = new RequestOptions({ headers: this.createHeader(headers) });

类型“标题”缺少类型中的以下属性 “标头”:键、值、toJSON、getAll 和另外 2 个.ts(2740) interfaces.d.ts(61, 5):预期类型来自属性 在“RequestOptionsArgs”类型上声明的“标头” (属性) RequestOptionsArgs.headers?: 标题

它也说warning

RequestOptions 已弃用:请参阅https://angular.io/guide/http (弃用)

【问题讨论】:

  • 您正在混合使用 2 个不同的 API:Http 和 HttpClient。坚持最新。
  • 我这样做是因为RequestOptions 不在@angular/common/http 中。有更好的例子吗?

标签: angular typescript rxjs angular7 ionic4


【解决方案1】:

试试

this.http.post(url, params, {headers: this.createHeader(headers)})

或者更好的是,查看HttpInterceptors 以获得通用标题

这里有个不错的tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 2010-09-26
    • 2018-06-15
    • 1970-01-01
    相关资源
    最近更新 更多