RequestOptions迁移Angular 5 [英] RequestOptions migration Angular 5

查看:65
本文介绍了RequestOptions迁移Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 4中使用了自定义请求选项,在其中执行以下操作:

I was using a custom request options in Angular 4 where I was doing the following:

default-request-options.service.ts

default-request-options.service.ts

@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {
  headers = new Headers({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  });

  merge(options?: RequestOptionsArgs): RequestOptions {
    var newOptions = super.merge(options);
    const token: string = localStorage.getItem('token');
    if (token) {
      newOptions.headers.set('token', token);
    }
    return newOptions;
  }
}

App.Module.ts

App.Module.ts

providers: [ // expose our Services and Providers into Angular's dependency injection
    { provide: RequestOptions, useClass: DefaultRequestOptions }
  ]

但是在迁移之后,请注意RequestOption在新文件夹http/common/http

But after the migration notice that the RequestOption is not available in the new folder http/common/http

我想知道我是否仍然可以在Angular 5中使用类似的东西,或者在新的HTTPClient中使用它没有意义吗?对我来说,主要优点是只设置在一个位置,而不必将其附加到我的所有请求中.

I'm would like to know if I still can use similar thing in Angular 5 or there is no point using it with the new HTTPClient? The main advantage for me was to set in one place only, not having to append it to all my requests.

我最初在angular文档中获得了代码:

I got the code initially in the angular docs: https://github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options.service.ts

推荐答案

您可以使用拦截器将默认标头添加到您的请求中.角度文档中的示例:

You can use interceptors to add default headers to your requests. Example from the angular docs:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth header from the service.
    const authHeader = this.auth.getAuthorizationHeader();
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
  }
}

这篇关于RequestOptions迁移Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆