【问题标题】:RequestOptions migration Angular 5RequestOptions 迁移 Angular 5
【发布时间】:2017-12-01 02:21:32
【问题描述】:

我在 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 }
  ]

但是迁移后提示RequestOption在新文件夹http/common/http中不可用

我想知道我是否仍然可以在 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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以使用interceptors 为您的请求添加默认标头。角度文档中的示例:

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

    【讨论】:

    • 看起来拦截器是一种可行的方法,正是我想要的,还有更多。 Tks
    • 嗨,我正在重构非常相似的服务,但是您从哪里获得“AuthService”?
    • 嗨,我怎样才能改变上传文件的“标题”值..?因为在上传文件时它也采用内容类型','应用程序/json'`,我想添加multipart/form-data。你能帮帮我吗?
    猜你喜欢
    • 2019-05-18
    • 2018-10-12
    • 2023-04-08
    • 2018-10-18
    • 2021-11-02
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多