Gam*_*ney 14 angular2-services angular
在我的Angular2应用程序中,我正在尝试使用HTTP在引导程序中从后端加载配置,以便我可以使用提取的数据来创建角度服务.
每当我尝试读取保存在我的Config中的HTTP响应时,我总是得到TypeError:无法读取未定义错误的属性'url'.
看起来HTTP请求仅在整个引导程序方法完成时才完成,而我的代码尝试在检索之前提取Observable响应.
如何修复它以从服务器中提取配置并使用它在启动时创建角度服务?(我想在提取数据的提供者中创建服务)
如果在启动时有更好的方法从服务器中提取配置,请发表评论.
我的main.ts看起来像这样:
bootstrap(AppComponent,
[APP_ROUTER_PROVIDERS, HTTP_PROVIDERS, ConfigurationService, Config])
.catch(err => console.error(err)
);
Run Code Online (Sandbox Code Playgroud)
configuration.service.ts
@Injectable()
export class ConfigurationService {
constructor(private http: Http) {
}
load() {
return this.http.get('config/getConfig').map(response => response.json());
}
}
Run Code Online (Sandbox Code Playgroud)
config.ts
@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];
}
}
Run Code Online (Sandbox Code Playgroud)
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
my.service.ts
@Injectable()
export class MyService{
private url;
constructor(public config: Config) {
this.url = config.get('url');
}
}
Run Code Online (Sandbox Code Playgroud)
Thi*_*ier 12
您可以APP_INITIALIZER
在应用程序启动之前利用该服务重新加载配置:
bootstrap(AppComponent, [
{
provide: APP_INITIALIZER,
useFactory: (config:Config) => {
return config.load();
},
dependency: [ Config ]
}
]);
Run Code Online (Sandbox Code Playgroud)
为此,你需要适应你的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();
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您将能够直接访问应用程序中配置对象的属性.
Dai*_*kša 10
使用AoT编译时,它会抛出错误,因为工厂是匿名函数.您需要做的是为工厂导出一个函数
export function ConfigLoader(configService: ConfigService) {
return () => configService.load();
}
Run Code Online (Sandbox Code Playgroud)
并且应用程序的配置如下所示:
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpModule,
BrowserModule
],
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: ConfigLoader,
deps: [ConfigService]
}],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)
参考https://github.com/angular/angular/issues/10789
归档时间: |
|
查看次数: |
9138 次 |
最近记录: |