我有一个像这样的 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 组件中的字符串中。类似于 nodeJS 中的 fs.ReadFileSync
API。我怎样才能做到这一点? HTTP 调用?文件阅读器?
最佳答案
简短的回答是您无法同步读取静态文件,因为它们依赖于浏览器的异步 API。
也就是说,您可以利用一个服务来加载您的所有资源,并等待该服务加载所有内容,然后再启动您的应用程序。 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;
}
}
有关详细信息,请参阅此问题:
关于node.js - 以字符串形式读取angular2中的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847512/