【问题标题】:Reading static files in angular2 as string将angular2中的静态文件作为字符串读取
【发布时间】:2016-12-15 07:25:19
【问题描述】:

我有一个这样的 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 调用?文件阅读器?

【问题讨论】:

    标签: node.js http angular angular2-template


    【解决方案1】:

    简短的回答是您无法同步读取静态文件,因为它们依赖于浏览器的异步 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;
      }
    }
    

    查看这个问题了解更多详情:

    【讨论】:

    • 非常感谢。在我的应用程序中,我只在一个子组件中使用这个“演示”组件,对于大多数用户来说,它不会被使用,所以我相信在引导程序中使用它会阻止每个用户,无论他们是否使用演示组件?如果这是正确的,有没有办法只“保留”&lt;demo&gt; 将在其中使用的组件?
    猜你喜欢
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多