如何扩展Angular HttpRequest参数?

时间:2018-01-19 02:51:35

标签: javascript angular typescript web

嗨,我是AngularJS的形式,而且是Angular的新版本。

  • AngularJS

在AngularJS $ http服务中,我可以为特定的HTTP请求添加一些自定义配置:

 $http.post('api/data-source/item'.assign(opts), opts.parameters, **ignoreUnauthorized**).then(...)

类似于此RestAPI的ignoreUnauthorized选项绕过全局http拦截器:

responseError: function(response) {
    if (response.status === 401 && !response.config.**ignoreUnauthorized**) {
        $rootScope.$broadcast('error:unauthorized', response);
        return $q.defer().promise;
    }
    return $q.reject(response);
}
  • Angular4.3 +

但在Angular HttpClient中,我们无法将这些属性添加到选项中,因为TypeScript从未允许我这样做。 我还尝试扩展HttpClient以添加额外选项:

export interface AppHttpParams {
    headers?: HttpHeaders;
    observe?: 'body';
    params?: HttpParams;
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
    body?: any;
    **ignoreUnauth**: boolean;
}

export function applicationHttpClientCreator(http: HttpClient) {
    return new AppHttpClient(http);
}

@Injectable()
export class AppHttpClient {
    public constructor(public http: HttpClient) {}
    ...
}

但是自定义选项 ignoreUnauth 似乎没有附带HttpRequest对象,HttpRequest对象中的所有属性似乎都是默认属性(从Chrome控制台输出):

HttpRequest {url: "http://...", body: null, reportProgress: false, withCredentials: false, responseType: "json", …}
  -body:null
  -headers:HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
  -method:"GET"
  -params:HttpParams {updates: null, cloneFrom: null, encoder: HttpUrlEncodingCodec, map: Map(0)}
  -reportProgress:false
  -responseType:"json"
  -url:"http://..."
  -urlWithParams:"http://..."
  -withCredentials:false
  -__proto__:Object

有没有办法将自己的选项添加到Angular中的HttpRequest,如AngularJS?或者还有其他方法可以扩展HttpRequest选项吗?

1 个答案:

答案 0 :(得分:1)

我正在使用http标头来实现这一目标。

只需将所需值设置为自定义http标头:

new HttpHeaders().set("X-my-custom-header", string | string[]);

然后您可以在http拦截器中将其删除(以避免公开显示)

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const request = req.clone({
      headers: req.headers
                 .delete("X-my-custom-header")
    });
    return next.handle(request).pipe(
      catchError(err => this.handleHttpError(err, req))
    );
  }

您可以在handleHttpError中使用该值(在此传递原始请求时):

const myCustomHeaderValue = req.headers.getAll("X-my-custom-header");