首页 > 解决方案 > 如何根据 url angular 2 创建对后端的动态请求

问题描述

我有一个 Angular 应用程序(它是生产版本)。应用程序可在两个链接(http://blabla.comhttp://test.com)。现在:对于您打开应用程序的任何 url,前端都会通过 url (test.com/api) 发送后端请求,因为它在环境中是硬编码的。我应该根据我拥有的 URL 向后端发出请求。例如,URL 是 blablabla.com,我必须创建一个请求来后端 blablabla/api

     private apiUrl = environment.apiUrl.replace(/[/]+$/, '');
    
     private getUrl(url: string): string 
        return `${this.apiUrl}/${url}`;
      }

     public get<TResponse extends ApiResponse<any>>(url: string, options?: ApiRequestOptions): Observable<any> {
    let requestUrl = this.getUrl(url);
    let httpOptions = this.getHttpOptions(options);
    if (options && options.observe) {
      return this.httpClient.get<TResponse>(requestUrl, {
        observe: options.observe,
        ...httpOptions,
      });
    } else {
      return this.httpClient.get<TResponse>(requestUrl, httpOptions);
    }
  }

    export const environment = {
      production: true,
      apiUrl: 'https://test.com/api/v1/',
    };

标签: angular

解决方案


如果您有服务前。getSomeDataService,你可以像这样注入你的组件并在那里使用。getSomeData.service.ts:

import {HttpClient, HttpHeaders} from '@angular/common/http';
...
// headers if they are needed

getDataBack(url: string) {
        return this.http.get(url);
    }

sometig.component.ts:

...
import {GetSomeDataService} from '../services/getSomeData.service';
...

// inject into constructor
constructor(private getSomeService: GetSomeDataService){}

// after that in ngOnInit or elsewhere

ngOnInit() {
   url = location.host+'/api'; // or location host
   this.getSomeService(url)
   .subscribe(response => console.log());
} 

更新
所以你有以下内容:

// hardcoded url which located in src/environment.prod.ts not necessary
 //private apiUrl = environment.apiUrl.replace(/[/]+$/, '');
    
     private getUrl(url: string): string 
        //return `${this.apiUrl}/${url}`;
        //here change the logic..
          return `${location.host}/${url}`;
      }

推荐阅读