angular - RequestOptions 迁移 Angular 5

标签 angular typescript

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

默认请求选项.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

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

但是迁移后发现新文件夹http/common/http中没有RequestOption

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

我最初在 Angular 文档中获得了代码:https://github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options.service.ts

最佳答案

您可以使用 interceptors为您的请求添加默认 header 。来自 Angular 文档的示例:

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);
  }
}

关于angular - RequestOptions 迁移 Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585720/

相关文章:

C#:将 "Class Library"项目用于插件

angular - 如何在没有 filterPredicate 的情况下以 Angular 过滤 MatTable

Angular 4 阻止路由器导出重新加载父组件

Angular 2 如何测试使用路由器的组件

java - Spring Boot-Angular - 在地址栏中输入 URL 会导致 404

Typescript 接口(interface)方法 Vs 抽象方法语法差异

node.js - Angular/Electron服务输出传递给变量,但返回未定义

angular - 属性 'features' 在类型 'Feature<Point, { [name: string]: any; }>' 上不存在

javascript - Angular2 - 根据对象属性的值过滤对象数组

typescript - 在 Typescript 中,模块的类型是什么?