Angular 6 Http客户端自定义URL和标头

问题描述 投票:2回答:1

我正在使用Angular 6应用程序,我想知道在向服务器发送请求时自定义URL时最佳做法是什么。

这是场景: - 在我的Angular项目中,我有environment.ts和environment.prod.ts,其中我添加了一个“host”,其中包含http服务器的url:port(带控制器的项目)。 - 我正在创建要注入我的组件的服务,这些服务将负责向服务器发送请求(GET和POST)以检索数据或发送更新。 - 我想使用environment.ts中的“host”作为请求URL的一部分。所以我的所有请求都将“主机”作为基本URL,然后我可以连接到所需的路径。

我已经检查了一些解决方案,我已经实现了其中一个,但我不确定这是正确的做法。我将在下面写下我到目前为止所实现的内容,然后我会写一些想法,请帮助我了解什么是最佳解决方案(我是新的角度)

目前实施:

- >在我的功能服务中,比如LoginService,我注入了角度HttpClient。然后我简单地打电话:

return this.httpService.post("/login/", creds).pipe(
      map((data: any) => {
        this.manager = data;
        return this.manager;
      }));

我创建了一个拦截器来更改url:InterceptService实现HttpInterceptor,我在其中创建HttpRequest的新实例并使用environment.host自定义request.url。我还需要拦截器为身份验证添加一个Header(仍未完全实现)

const httpRequest = new HttpRequest(<any>request.method, environment.host + request.url, request.body);
    request = Object.assign(request, httpRequest);

    const headers = new HttpHeaders({
      'Authorization': 'Bearer token 123',
      'Content-Type': 'application/json'
    });

问题:

1)这个工作,所有我的请求都在我想要的拦截器中更改,但它看起来不像我第一次看的最佳实践。我不喜欢创建一个新的HeepRequest来做到这一点(我这样做是为了让它保持不变,我猜这是正确的方法)。你觉得这看起来不错吗?

2)在拦截器中添加到Header的身份验证怎么样?好吗?我检查的大多数参考文献都是这样做的

其他方案:

1)我看到了一些示例,其中HttpClientService扩展了Http,并且在调用超级方法之前,每个方法(如get和post编辑url和headers)都是如此。但我相信这不是Angular 6,可能不是优先考虑的

2)我还可以通过注入创建一个接收角度HttpClient(角度6 HttpClientModule)实例的服务,我可以实现get或post等方法。

httprequest httpclient angular6 interceptor base-url
1个回答
1
投票

好吧,由于我没有得到任何答案,我将添加我的解决方案。我认为这是基于我的研究的最佳解决方案。

我使用拦截器向标头添加信息,例如令牌承载认证。

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
  HttpHeaders,
  HttpErrorResponse
} from '@angular/common/http'
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { environment } from "../../../environments/environment";
import { Router } from "@angular/router";

export class HttpClientInterceptor implements HttpInterceptor {

  constructor(private router: Router) { }

  // intercept request to add information to the headers such as the token
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    //I decided to remove this logic from the interceptor to add the host url on the HttpClientService I created
    //const httpRequest = new HttpRequest(<any>request.method, environment.host + request.url, request.body);
    //request = Object.assign(request, httpRequest);

    var token = localStorage.getItem("bearerToken");

    if (token) {
      const newReq = request.clone(
        {
          headers: request.headers.set('Authorization',
            'Bearer ' + token)
        });

      return next.handle(newReq).pipe(
        tap(event => {
          if (event instanceof HttpResponse) {
            console.log("Interceptor - HttpResponse = " + event.status); // http response status code
          }
        }, error => {
          // http response status code
          if (error instanceof HttpErrorResponse) {
            console.log("----response----");
            console.error("status code:");
            console.error(error.status);
            console.error(error.message);
            console.log("--- end of response---");

            if (error.status === 401 || error.status === 403) //check if the token expired and redirect to login
              this.router.navigate(['login']);
          }
        })
      )
    }
    else {
      return next.handle(request);
    }
  };

为了更改URL,我在文件http-client.service.ts上创建了一个服务,并从environment.ts获取了主机URL

import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { Observable } from "rxjs";
import { environment } from "../../../environments/environment";

@Injectable({ providedIn:'root' })
export class HttpClientService {
  constructor(private http: HttpClient) { }

  get(url: string, options?: any): Observable<ArrayBuffer> {
    url = this.updateUrl(url);
    return this.http.get(url, options);
  }

  post(url: string, body: string, options?: any): Observable<ArrayBuffer> {
    url = this.updateUrl(url);
    return this.http.post(url, body, options);
  }

  put(url: string, body: string, options?: any): Observable<ArrayBuffer> {
    url = this.updateUrl(url);
    return this.http.put(url, body, options);
  }

  delete(url: string, options?: any): Observable<ArrayBuffer> {
    url = this.updateUrl(url);
    return this.http.delete(url,options);
  }

  private updateUrl(req: string) {
    return environment.host + req;
  }
}

正如我所说,我认为这是最好的方法,但随时可以在我的问题/答案中添加信息。

© www.soinside.com 2019 - 2024. All rights reserved.