这种方式对我们非常有用:
- 创建一个自定义 HTTP 服务并构建一个检查当前 URL 的函数。
custom-http.service.ts <-您可以将其命名为您的公司/应用程序名称
@Injectable()
export class CustomHttpService {
constructor(private http: HttpClient) {
}
public getCurrentEnvironment(): string {
const host = window.location.origin;
let env = "";
switch(host) {
case 'http://localhost:4200': {
env = 'LOCALDEV';
break;
}
case 'https://my-test-site.azurewebsites.net': {
env = 'TEST';
break;
}
case 'https://my-prod-site.azurewebsites.net': {
env = 'PROD';
break;
}
case 'https://customdomain.com': {
env = 'PROD';
break;
}
default: {
env = 'PROD';
break;
}
}
return env;
}
public get(url: string): Observable<any> {
return this.http.get(url);
}
public getWithHeader(url: string, header: HttpHeaders): Observable<any> {
return this.http.get(url, {headers: header});
}
public post(url: string, body: any): Observable<any> {
return this.http.post(url, body);
}
public put(url: string, body: any): Observable<any> {
return this.http.put(url, body);
}
public delete(url: string): Observable<any> {
return this.http.delete(url);
}
}
您可以从应用程序中的任何位置调用 getCurrentEnvironment() 以了解您所处的环境。
- 创建一个 URL 帮助服务,这将为您的特定环境传递正确的 API url。
@Injectable()
export class URLHelper {
constructor(private httpService: CustomHttpService) {
}
private env: string = this.httpService.getCurrentEnvironment();
private Server: string = this.getServerUrl(this.env);
getServerUrl(env: string): string {
let server = "";
switch (env) {
case "LOCALDEV": {
server = "http://localhost/project/";
break;
}
case "TEST": {
server = "https://my-test-site-api.azurewebsites.net/";
break;
}
case "PROD": {
server = "https://my-prod-site-api.azurewebsites.net/";
break;
}
default: {
console.error('No Env Found');
server = "https://my-prod-site-api.azurewebsites.net/";
}
}
return server;
}
// Here you will define all the API endpoints your app will use and 'this.Server ' will contain the proper host API server url at runtime for each environment.
public User = this.Server + 'api/User';
- 用法。要现在使用它,您需要做的就是在任何功能模块服务中,将 CustomHttpService 和 URLHelper 添加到构造函数中
@Injectable()
export class AdminService {
constructor(private urlHelper: URLHelper, private httpService: CustomHttpService) { }
getUser(): Observable<any> {
return this.httpService.get(this.urlHelper.User);
}
}