sourcetip

Angular Http Client의 baseUrl은 어떻게 설정합니까?

fileupload 2023. 8. 26. 12:08
반응형

Angular Http Client의 baseUrl은 어떻게 설정합니까?

설명서에서 HTTP 요청에 대한 기본 API URL을 설정하는 방법을 찾지 못했습니다.Angular Http Client에서 이 작업을 수행할 수 있습니까?

새 HttpClient Interceptor를 사용합니다.

다음을 구현하는 적절한 주입 가능 파일을 만듭니다.HttpInterceptor:

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

@Injectable()
export class APIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const apiReq = req.clone({ url: `your-api-url/${req.url}` });
    return next.handle(apiReq);
  }
}

HttpInterceptor는 요청을 복제하고 원하는 대로 변경할 수 있습니다. 이 경우 모든 http 요청에 대한 기본 경로를 정의했습니다.

HttpClientModule에 다음 구성을 제공합니다.

providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: APIInterceptor,
      multi: true,
    }
  ]

이제 모든 요청은 다음과 같이 시작됩니다.your-api-url/

에 기반을 둔TheUnreal의 매우 유용한 답변으로 인터셉트를 작성하여 DI를 통해 기본 URL을 가져올 수 있습니다.

@Injectable()
export class BaseUrlInterceptor implements HttpInterceptor {

    constructor(
        @Inject('BASE_API_URL') private baseUrl: string) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const apiReq = request.clone({ url: `${this.baseUrl}/${request.url}` });
        return next.handle(apiReq);
    }
}

BASE_API_URL응용 프로그램 모듈에서 제공할 수 있습니다.

providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: BaseUrlInterceptor,
    multi: true
  },
  {
    provide: "BASE_API_URL", useValue: environment.apiUrl
  }
]

어디에environment프로젝트를 생성할 때 CLI에 의해 자동으로 생성되는 개체입니다.

export const environment = {
  production: false,
  apiUrl: "..."
}; 

Alexei를 팔로우했지만 나처럼 작동하지 못한 모든 사람이 대답합니다. 이는 공급자 어레이에도 이 요소를 추가해야 하기 때문입니다.

{
  provide: HTTP_INTERCEPTORS,
  useClass: BaseUrlInterceptor,
  multi: true
}

안타깝게도 저는 그의 답변에 코멘트를 덧붙이기에는 평판이 너무 낮습니다.

baseUrl을 구성할 수 있는 HttpClient 하위 클래스를 만드는 것은 어떻습니까?이렇게 하면 응용 프로그램이 여러 서비스와 통신해야 하는 경우 각 서비스에 대해 다른 하위 클래스를 사용하거나 구성이 서로 다른 단일 하위 클래스의 인스턴스를 여러 개 생성할 수 있습니다.

@Injectable()
export class ApiHttpClient extends HttpClient {
  public baseUrl: string;

  public constructor(handler: HttpHandler) {
    super(handler);

    // Get base url from wherever you like, or provision ApiHttpClient in your AppComponent or some other high level
    // component and set the baseUrl there.
    this.baseUrl = '/api/';
  }

  public get(url: string, options?: Object): Observable<any> {
    url = this.baseUrl + url;
    return super.get(url, options);
  }
}

Visual studio 2017 asp.net core webapi 각진 샘플 애플리케이션에서 발췌.

Main.ts에 아래 줄 포함

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

귀하의 구성 요소에서

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }

나의 완전한 main.ts 코드는 아래와 같습니다.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

나의 구성 요소 코드는 아래와 같습니다.

import { Component, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'fetch-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.scss']
})

export class WeatherComponent {
  public forecasts: WeatherForecast[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }
}

interface WeatherForecast {
  dateFormatted: string;
  temperatureC: number;
  temperatureF: number;
  summary: string;
}

HttpClient와 함께 기본 URL이 반드시 필요한 것은 아닙니다. 문서에 따르면 요청의 api 부분만 지정하면 됩니다. 동일한 서버에 호출하는 경우 다음과 같이 간단합니다.

this.http.get('/api/items').subscribe(data => {...

그러나 필요하거나 원하는 경우 기본 URL을 지정할 수 있습니다.

이를 위한 두 가지 제안이 있습니다.

정적 클래스 속성을 가진 도우미 클래스입니다.

export class HttpClientHelper {

    static baseURL: string = 'http://localhost:8080/myApp';
}


this.http.get(`${HttpClientHelper.baseURL}/api/items`); //in your service class

새 서비스가 확장해야 하는 클래스 속성을 가진 기본 클래스:

export class BackendBaseService {

  baseURL: string = 'http://localhost:8080/myApp';

  constructor(){}
}

@Injectable()
export class ItemsService extends BackendBaseService {

  constructor(private http: HttpClient){  
    super();
  }
      
  public listAll(): Observable<any>{    
    return this.http.get(`${this.baseURL}/api/items`);
  }

}

저는 이것을 하기 위한 기본적인 방법은 없다고 생각합니다.HttpService를 수행하고 내부에서 기본 URL의 속성을 정의하고 속성 URL로 http.get 등을 호출하는 방법을 만들 수 있습니다.그런 다음 HttpClient 대신 HttpService를 삽입합니다.

언급URL : https://stackoverflow.com/questions/45735655/how-do-i-set-the-baseurl-for-angular-httpclient

반응형