读取angular2中的静态文件为string
我有一个这样的angular2组件:
@Component({ selector: 'demo', template: ` <div [innerHTML]="content"></div> `; }) export class demoComponent { @Input() step: string; private content: string = ''; ngOnInit () { if (this.step === "foo") { this.content = "bar"; } } }
我想用一些逻辑来决定最合适的模板来渲染。 我在myDomain.com/templates上有一系列由express提供的静态html文件。 所以我需要能够“读取” ./templates/xyz.html
到我的ng2组件中的string。 与fs.ReadFileSync
中的fs.ReadFileSync
API类似。 我怎样才能做到这一点? HTTP调用? 文件阅读器?
简单的答案是你不能同步读取静态文件,因为它们依赖于浏览器的asynchronousAPI。
也就是说,您可以利用服务来加载所有资源,并在启动应用程序之前等待此服务加载所有内容。 APP_INITIALIZER
服务允许你这样做。
这是一个示例:
bootstrap(AppComponent, [ { provide: APP_INITIALIZER, useFactory: (service:GlobalService) => () => service.load(), deps:[GlobalService, HTTP_PROVIDERS], multi: true } ]);
加载方法喜欢这样的事情:
load():Promise<Site> { return new Promise(resolve => { this.http.get('somestaticfile.html') .map(res => res.text() }) .subscribe(text => { this.staticContent = text; }); }); }
然后,您可以在应用程序中同步使用staticContent
属性:
@Component({ selector: 'demo', template: ` <div [innerHTML]="content"></div> ` }) export class demoComponent { @Input() step: string; private content: string; constructor(service:GlobalService) { this.content = service.staticContent; } }
看到这个问题的更多细节:
- Angular 2 – 在调用方法之前服务其他服务