node.js - 以字符串形式读取angular2中的静态文件

标签 node.js http angular angular2-template

我有一个像这样的 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/

相关文章:

angular - Bootstrap 5 工具提示在 Angular 11 项目中不起作用

node.js - 错误 : (gcloud. 预览.app.deploy)

javascript - node-webkit 从外部源运行函数

http - 我们可以使用 TLS over TCP 协议(protocol)吗?

Angular 6 错误 : CSSSyntaxError - Failed to compile

javascript - Angular Highcharts - 如何动态克隆图表

node.js - 带 Sequelize 的加法和减法赋值运算符

javascript - 在浏览器中进行语音聊天?

node.js - 在 Node 中仅获取 GET 请求的 header

android - Titanium android 设备 http 错误