我想从外部json文件配置我的Angular 2应用程序。
在我的 main.ts 中,我加载 config.json
getHttp().get('/config.json')
.map(response => response.json();)
.subscribe(
data => {
let clientConf: ClientConfig = data;
// here I want to pass clientConf to AppModule
platformBrowserDynamic().bootstrapModule(AppModule);
});
我想知道如何将 clientConf 传递给AppModule,以便在 app.module.ts 中使用
@NgModule({
...
providers: [
{ provide: Configuration, useValue: clientConf }
...
答案 0 :(得分:3)
这是我的解决方案:
....
.subscribe(
data => {
let clientConf: ClientConfig = data;
// here I want to pass clientConf to AppModule
platformBrowserDynamic(
[{ provide: ClientConfig, useValue: clientConf }]
).bootstrapModule(AppModule);
});
我没有将 clientConf 传递给 AppModule ,我为 platformBrowserDynamic设置 ClientConfig 为 extraProvider 而不是。
然后,如果你想使用 ClientConfig ,只需注入它:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private clientConfig: ClientConfig) { }
.....
答案 1 :(得分:0)
如果您想在加载UI之前获取数据,可以尝试使用路线保护。它们将允许您阻止用户导航到应用程序中的路径,直到条件成立为止。
您可以从路线防护中返回一个观察者,允许异步防护。
进一步阅读Angular route guards。
编辑:使用路由gaurd的resolve属性最适合等待数据。
答案 2 :(得分:0)
我很难遵循@ tomas-marik接受的答案,我认为这很好。以下是我在main.ts中用于Angular 8的改编:
fetch('/assets/config.json').then(async res => {
var clientConf = <ClientConfig>await res.json();
platformBrowserDynamic(
[{ provide: ClientConfig, useValue: clientConf }]
).bootstrapModule(AppModule)
.catch(err => console.error(err));
});