如何引导异步的角2应用程序 [英] How to bootstrap an Angular 2 application asynchronously

查看:141
本文介绍了如何引导异步的角2应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个<一个href=\"https://blog.mariusschulz.com/2014/10/22/asynchronously-bootstrapping-angularjs-applications-with-server-side-data\"相对=nofollow>如何引导异步的angular1应用优秀文章。这使我们能够从服务器获取引导前一个JSON。

There is an excellent article of how to bootstrap an angular1 application asynchronously. This enables us to fetch a json from the server before bootstrapping.

主要code是在这里:

The main code is here:

(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"]);
        });
    }
}());

我如何达到同样的角度用2?

How do I achieve the same with Angular 2?

推荐答案

在事实上,你需要明确创建应用程序本身之外的注射器获得 HTTP 的一个实例执行请求。然后加载的配置可以在供应商boostrapping应用程序时添加。

In fact, you need to create explicitly an injector outside the application itself to get an instance of Http to execute the request. Then the loaded config can be added in the providers when boostrapping the application.

下面是一个例子:

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 })
    ]);
  });

然后你可以通过依赖注入访问配置:

Then you can have access to the configuration by dependency injection:

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

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

看到这个plunkr: https://plnkr.co/edit/kUG4Ee9dHx6TiJSa2WXK?p = preVIEW

这篇关于如何引导异步的角2应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆