我有一个从Web API请求一些JSON数据的服务:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ReviewService {
private actionUrl: string;
constructor(private _http: Http) {
this.actionUrl = 'http://api.dc-shop.com/review';
}
public GetAll = (): any => {
return this._http.get(this.actionUrl)
.map(x => x.json());
}
}
[我想避免在构造函数中对API地址进行硬编码,而是从appSettings.json
中读取一个设置,该设置可以在生产服务器和localhost服务器启动时用作操作URL。
在ASP.NET MVC Core中执行此操作的最佳方法是什么?
我可以想到的两个选择:
1)将组态同时放在environment.ts
和appSettings.json
中-对此的访问内置于angular中。
2)服务的第1步使用简单的appSettings.json
加载http.get
,然后从中使用配置加载所需的数据。
environment.ts示例
export const environment = {
apiUrl: 'http://api.dc-shop.com',
mode: 'prod'
};
示例用法:
import { environment } from './environment';
constructor(private _http: Http) {
this.actionUrl = environment.apiUrl + '/review';
}
您可以使用Angular Http Intercepter来实现
在每个请求中添加http://api.dc-shop.com前缀。
示例代码:
在Angular应用中编写请求拦截器:
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let req_url = req.url
req.clone({url:`http://api.dc-shop.com/${req_url}`})
return next.handle(req);
}
}
并且在您的主模块中:
export const httpInterceptorProviders = [
{provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true},
}
@NgModule({
providers: [...,httpInterceptorProviders]
})
如果要在其他环境中配置前缀URL:
您可以在environment.xx.ts
下的/src/environments
中定义它>
并在angular.json中定义构建配置
.... "configurations": { "api": { .... "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.api.ts" } ] } .... } ...
以及在构建应用程序时,
仅添加配置
ng build --configuration=api
祝你好运!