1

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>
DragonBorn
  • 1,809
  • 5
  • 20
  • 44
Lemmy
  • 103
  • 1
  • 1
  • 8
  • 1
    do you want to bootstrap when that data is available? or do you want to hide your app until data is available and dont care about bootstrapping? – Ahmed Musallam Apr 10 '17 at 14:29
  • @Ahmed Musallam, it would be nice to show a 'Loading...' screen, then lazy load the application after initial user data is available. – Wallace Howery Jan 23 '18 at 18:13

1 Answers1

0

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>
Joshua Hall
  • 5
  • 1
  • 3
Ahmed Musallam
  • 9,523
  • 4
  • 27
  • 47