Bootstrapping Hybrid Angular 1+2 Application

Following the official 5 min QuickStart I have a simple Angular 2 app working.

I set up Angular 1 and have now them both working independently, see this plunker.

Following the official upgrade guide they say:

To then switch the application into hybrid mode, we must first install Angular 2 to the project. Follow the instructions in the QuickStart for some pointers on this. When we have Angular 2 installed, we can import and instantiate the UpgradeAdapter , and then call its bootstrap method. It is designed to take the exact same arguments as angular.bootstrap so that it is easy to make the switch:

import {UpgradeAdapter} from 'angular2/upgrade';

/* . . . */

const upgradeAdapter = new UpgradeAdapter();

upgradeAdapter.bootstrap(document.body, ['heroApp'], {strictDi: true});

My question is where to place it ?

It sounds like a 'do my job' question but it's not so. I guess in main.ts , but I tried a lot of things without success. The doc is not really clear about this and some tutorials of 1 month old are already outdated.

--- update:

In my case I forgot to load upgrade.js that I thought already included


I had a look at your plunkr. In fact you can use several times bootstrap but this means that you use two different applications into your HTML page.

If you want to mix Angular1 and Angular2 stuff into the same application, you need to call only the boostrap method of the UpgradeAdapter .

The call of the boostrap function on the UpgradeAdapter and it's creation could be done in the boot.ts file:

import {UpgradeAdapter} from 'angular2/upgrade';

var upgrade = new UpgradeAdapter();

// Configure the upgrade adapter
(...)

export function main() {
  try {
    upgrade.bootstrap(document.body, ['heroApp']);
  } catch (e) {
    console.error(e);
  }
}

You can import this into your HTML file like this:

<script>
  System.import('app/main').then(function(src) {
    src.main();
  });
</script>

Mixing Angular2 and Angular1 stuff

If you want to bootstrap an Angular2 application , provide the main component as first parameter and the provider for the Angular1 application to be able to use factories / services / directives into the Angular2 application.

// Providers for Angular1 elements
upgrade.upgradeNg1Provider('customService');
upgrade.upgradeNg1Provider('customFactory');

// Providers for Angular2 elements
upgrade.addProvider(HTTP_PROVIDERS);

// Bootstrap Angular2 application
upgrade.bootstrap(AppComponent);

If you want an Angular1 application to use Angular2 stuff , you need to provide the document.element as first parameter of the bootstrap method:

// Providers for Angular2 elements
upgrade.downgradeNg2Provider(HTTP_PROVIDERS);

upgrade.bootstrap(document.body, ['heroApp']);

This plunkr could also be useful to you: http://plnkr.co/edit/yMjghOFhFWuY8G1fVIEg?p=preview.

链接地址: http://www.djcxy.com/p/90264.html

上一篇: 路由器:`<链接到= ...>`不会触发导航改变

下一篇: Bootstrapping混合角1 + 2应用程序