微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-来自外部数据的Angular 2 Bootstrap应用程序

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

解决方法:

从这里开始:
plnkr:https://plnkr.co/edit/b0XlctB98TLECBVm4wps

您可以在窗口对象上设置URL:请参见下面的index.html.
在您的根组件中,添加* ngif =“ ready”,其中ready是您的根组件的公共成员,认情况下设置为false.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐