[英]Angular2 load configuration from backend on startup
在我的 Angular2 應用程序中,我嘗試使用 HTTP 從引導程序的后端加載配置,以便我可以使用提取的數據來創建角度服務。
每當我嘗試讀取保存在我的配置中的 HTTP 響應時,我總是得到TypeError: Cannot read property 'url' of undefined error。
看起來 HTTP 請求僅在整個引導方法完成時才完成,而我的代碼嘗試在檢索之前提取 Observable 響應。
如何修復它以從服務器提取配置並在啟動時使用它來創建角度服務? (我想用提取的數據在提供者內部創建服務)
請評論是否有更好的方法在啟動時從服務器中提取配置。
我的main.ts看起來像這樣:
bootstrap(AppComponent,
[APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
.catch(err => console.error(err)
);
配置.service.ts
@Injectable()
export class ConfigurationService {
constructor(private http: Http) {
}
load() {
return this.http.get('config/getConfig').map(response => response.json());
}
}
配置文件
@Injectable()
export class Config {
public config;
constructor(public configurationService: ConfigurationService) {
configurationService.load().subscribe(
config => this.config = config,
error => console.error('Error: ' + error)
);
}
get(key: any) {
return this.config[key];
}
}
app.component.ts
@Component({
selector: 'app',
templateUrl: 'app/app.component.html',
styleUrls: ['app/app.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [MyService]
})
export class AppComponent {
constructor(public myService: MyService) {
}
}
我的.service.ts
@Injectable()
export class MyService{
private url;
constructor(public config: Config) {
this.url = config.get('url');
}
}
您可以利用APP_INITIALIZER
服務在應用程序啟動之前重新加載配置:
bootstrap(AppComponent, [
{
provide: APP_INITIALIZER,
useFactory: (config:Config) => {
return config.load();
},
dependency: [ Config ]
}
]);
為此,您需要對ConfigService
類進行一些調整:
@Injectable()
export class ConfigService {
constructor(private http:Http) {}
load() { // <------
return new Promise((resolve) => {
this.http.get(...).map(res=>res.json())
.subscribe(config => {
this.config = config;
resolve();
});
}
}
然后,您將能夠直接訪問應用程序中配置對象的屬性。
使用 AoT 編譯時會引發錯誤,因為工廠是匿名函數。 然后你需要做的是為工廠導出一個函數
export function ConfigLoader(configService: ConfigService) {
return () => configService.load();
}
應用程序的配置如下所示:
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpModule,
BrowserModule
],
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: ConfigLoader,
deps: [ConfigService]
}],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
這是編寫加載函數的更好方法
public load() {
let promise =this.http.get(url).map(res => res.json()).toPromise();
promise.then(config => this.validation = config);
return promise;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.