1

如何仅在获取外部数据后加载 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>

4

1 回答 1

0

这是开始的内容:plnkr:https ://plnkr.co/edit/b0XlctB98TLECBVm4wps

您可以在窗口对象上设置 URL:见index.html下文。在根组件中,添加*ngif="ready"where ready 是根组件的公共成员,默认设置为 false。

然后在您的服务/根组件中使用该 URL 和 http 服务,一旦请求成功,您可以将 ready 设置为 true,您的应用程序将显示:查看app.ts app组件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: 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 {}

文件:src/data.json

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

文件:src/index.html

<header>
    ...
    <script>window['myUrl'] = 'data.json'</script>
    ...
</header>
于 2017-04-10T14:46:47.080 回答