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>
标签:javascript,angular,typescript,angular-cli,angular2-bootstrapping 来源: https://codeday.me/bug/20191009/1878288.html