通过HTTP CRUD工作流程上的通用方法发送标头

时间:2019-03-03 15:48:29

标签: angular typescript rxjs angular7 ionic4

我有这样的服务

注意:在这里,我需要使用ExceptionHandler

@ControllerAdvice
public class DemoControllerAdvice {

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<String> handleIOException(HttpRequestMethodNotSupportedException ex) {
        // prepare responseEntity
        return ResponseEntity.notFound().build();
    }

}

您可以看到我必须发送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; } } 错误

  

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

它也说compile time

  

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

1 个答案:

答案 0 :(得分:0)

尝试

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

甚至更好,请查看HttpInterceptors中的通用标头

还有一个不错的tutorial