如何在 Angular Typescript 中设置 BASE_URL?

How to set up BASE_URL in Angular Typescript?

我正在尝试将 BASE_URL 注入到我的所有组件的 TS 文件中。但我不确定它在哪里创建或如何设置?

我试图避免为每个文件写出完整的 URL,以避免必须根据我 运行 它所在的设备或是否部署它来更改它。现在我把它设置成一个字符串

"localhost:44347/*whatever*"

我希望能够注入 URL 的本地主机或基础部分,而不必事先知道我使用的是哪个端口。这可能吗?你会怎么做?

EX:(这是我希望看到的理想情况)

 constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
  }

  getUrl(): Observable<any[]> {
    return this.http.get<any[]>(baseUrl)
  }

编辑:

这是我尝试实现的,但是我仍然无法在我的函数中使用 'baseUrl'。

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

 getUrl(): Observable<any[]> {
        return this.http.get<any[]>(baseUrl)
      }

您应该能够在项目或库中的某处设置 InjectionToken

像下面这样的东西应该适合你:

export const BASE_URL: InjectionToken<string> = new InjectionToken<string>('baseURL');

然后在您的应用模块中为您的令牌添加一个提供程序到提供程序数组:

{ provide: BASE_URL, useValue: 'localhost:44347/*whatever*'}

从那里你应该可以像上面的例子一样注入。