Search code examples
javascriptangulartypescriptangular-cliangular2-bootstrapping

Angular 2 Bootstrap application from external data


How to load Angular 2 application only after getting external data?

For example, there is external application on the same html page, I need pass some data to my app service. Imagine, this is API URL, like 'some_host/api/' and my application should not be initialized till getting this information.

Is it possible to call some method of the my application from external app script like:

application.initApplication('some data string', some_object);

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>App</title>
  <base href="/">
  <link>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<script>
  application.initApplication('api/url', some_object);
</script>


  <app-root
   >Loading...</app-root>

</body>
</html>


Solution

  • 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>