Angular 2从外部数据引导应用程序

问题描述:

如何仅在获取外部数据后才加载Angular 2应用程序?Angular 2从外部数据引导应用程序

例如,在同一个html页面上有外部应用程序,我需要将一些数据传递给我的应用程序服务。想象一下,这是API URL,像'some_host/api/'和我的申请不应该被初始化,直到得到这些信息。

是否可以调用我的应用程序的一些方法从外部应用程序的脚本,如:

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>

+1

你想,当这些数据可用来引导?或者你想隐藏你的应用程序,直到数据可用,不关心引导? –

+0

@Ahmed Musallam,最好显示一个“Loading ...”屏幕,然后在初始用户数据可用后延迟加载应用程序。 – user2748659

这里的东西入手: plnkr:https://plnkr.co/edit/b0XlctB98TLECBVm4wps

您可以在窗口对象上设置url:请参阅下面的。 在你的根组件中,添加*ngif="ready"准备好是默认情况下设置为false的根组件的公共成员。

然后使用该网址在服务/根组件与HTTP服务,一旦申请成功,你可以设定成准备真正和你的应用程序会显示:看到app.tsapp组件ngOnInit方法。

代码:

文件: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: false; 
    constructor(private http: Http) { 
    this.name = `Angular! v${VERSION.full}` 
    } 
    ngOnInit(){ 
    var self = this; 
    var 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 {} 

文件:src/data.json

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

文件:src/index.html

<header> 
    ... 
    <script>window['myUrl'] = 'data.json'</script> 
    ... 
</header>