angularjs - 如何异步引导 Angular 2 应用程序

标签 angularjs angular

有一个excellent article如何异步引导 angular1 应用程序。这使我们能够在引导之前从服务器获取 json。

主要代码在这里:

(function() {
    var myApplication = angular.module("myApplication", []);

    fetchData().then(bootstrapApplication);

    function fetchData() {
        var initInjector = angular.injector(["ng"]);
        var $http = initInjector.get("$http");

        return $http.get("/path/to/data.json").then(function(response) {
            myApplication.constant("config", response.data);
        }, function(errorResponse) {
            // Handle error case
        });
    }

    function bootstrapApplication() {
        angular.element(document).ready(function() {
            angular.bootstrap(document, ["myApplication"]);
        });
    }
}());

如何使用 Angular 2 实现同样的效果?

最佳答案

事实上,您需要在应用程序本身之外显式创建一个注入(inject)器,以获取 Http 的实例来执行请求。然后可以在引导应用程序时将加载的配置添加到提供程序中。

这是一个示例:

import {bootstrap} from 'angular2/platform/browser';
import {provide, Injector} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {AppComponent} from './app.component';
import 'rxjs/Rx';

var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);

http.get('data.json').map(res => res.json())
  .subscribe(data => {
    bootstrap(AppComponent, [
      HTTP_PROVIDERS
      provide('config', { useValue: data })
    ]);
  });

然后你就可以通过依赖注入(inject)访问配置了:

import {Component, Inject} from 'angular2/core';

@Component({
  selector: 'app',
  template: `
    <div>
      Test
    </div>
  `
})
export class AppComponent {
  constructor(@Inject('config') private config) {
    console.log(config);
  }
}

查看此插件:https://plnkr.co/edit/kUG4Ee9dHx6TiJSa2WXK?p=preview .

关于angularjs - 如何异步引导 Angular 2 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180108/

相关文章:

javascript - 为什么 angularjs 无法正确解析我的对象?

Angular 8 延迟加载语法不起作用

angular - 使用 forRoot() 导入模块

javascript - AngularJS - Controller 内的函数没有像我在简单示例中所期望的那样被调用

Html css 用 angularJS 证明故障

javascript - 从组件调用的 Angular 4 指令的多个实例弄乱了输入值

javascript - 创建 Angular 项目时出错

regex - Primeng KeyFilter 运行不正常

javascript - 您如何在 EmberJs 应用程序中将所有 HTTP 请求设为 'intercept'?

javascript - browser.pause() 和 browser.enterRepl() 有什么区别?