从本地或 heroku/deployed 服务器获取

Fetch either from local or from heroku/deployed server

我在本地开发我的应用程序,但在完成一些任务后,我将它部署到 netlify 上以检查它的运行情况。 我想根据我提供应用程序的位置切换我的提取请求 (local/netlify)

这是我的auth.service.ts,我应该实现哪个逻辑?

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const baseUrl = 'http://localhost:3001'
const deployedUrl = 'https://my-deployed-server.herokuapp.com'

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private http: HttpClient) { }

  login(user:any){
    return this.http.post(`${baseUrl}/login`, user, {observe: "body", responseType:"json"})
  }

  signup(user:any){
    return this.http.post(`${baseUrl}/signup`, user, {observe: "body", responseType:"json"})
  }
}

感谢您的帮助

您应该创建不同的 .env 文件。在您的项目中,您应该在该文件夹中有一个名为 enviorment 的文件夹,您应该至少有两个文件:environment.tsenvironment.prod.ts(您可以根据需要添加任意数量的环境文件)。在这些文件中,您可以声明不同的变量。因此,在您的情况下,您必须再创建一个 env 文件(我假设 heroku 版本将是您的生产环境)。

// 文件 environment.prod.ts

export const environment = {
  production: true,
  api: 'https://my-deployed-server.herokuapp.com'
};

// 文件 environment.dev.ts

export const environment = {
  production: true,
  api: 'localhost:{your-port here}'
};

之后,在您的服务中,您将照原样使用 env 文件

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { enviorment } from 'environments/environment'

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private http: HttpClient) { }

  login(user:any){
    return this.http.post(`${enviorment.apiUrl}/login`, user, {observe: "body", responseType:"json"})
  }

  signup(user:any){
    return this.http.post(`${enviorment.apiUrl}/signup`, user, {observe: "body", responseType:"json"})
  }
}

这里重要的是你应该从基础 environment 文件(不是 .prod 、 .dev 路径)导入 environment 变量。根据您的构建配置,基本环境文件将被其他一些环境文件覆盖。因此,如果您 build/serve 您的生产应用程序, apiUrl 将指向远程服务器,如果您 build/serve 用于开发, apiUrl 将是 localhost

您可以了解有关文件替换的更多信息here and about the build configurations here