Angular 2 Bootstrap application from external data

元气小坏坏 提交于 2019-12-01 13:33:54
Ahmed Musallam

Here is something to start with: plnkr: https://plnkr.co/edit/b0XlctB98TLECBVm4wps

You can set the URL on the window object: see index.html below. In your root component, add *ngif="ready" where ready is a public member of your root component that is set to false by default.

Then use that URL in your service/root component with http service, once the request is successful you can set ready to true and your app will show: see app.ts app component ngOnInit method.

Code:

File: src/app.ts

import { Component, NgModule, VERSION, OnInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, Http } from '@angular/http';

@Component({
  selector: 'my-app',
  template: `
    <div *ngIf="ready">
      <h2>Hello {{name}}</h2>
    </div>
  `,
});

export class App implements OnInit {
  name: string;
  ready: boolean;
  constructor(private http: Http) {
    this.name = `Angular! v${VERSION.full}`
  }
  ngOnInit(){
    const self = this;
    const url = window["myUrl"];
    this.http.get(url)
    .subscribe(
      (res) =>
      {
        // do something with res
        console.log(res.json())
        self.ready = true;
      },
      (err) => console.error(err)),
      () => console.log("complete"))
  }
}

@NgModule({
  imports: [ BrowserModule, HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

File: src/data.json

{
  "key1": "val1",
  "key2": "val2"
}

File: src/index.html

<header>
    ...
    <script>window['myUrl'] = 'data.json'</script>
    ...
</header>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!