Angular2 - ComponentResolver

Ng2 RC了变化很多.这个是群友Twitter上找到的一个动态加载的例子.

不同于动态加载本地的组件,这个牛逼在加载远程的

import {Component, ViewChild, ViewContainerRef, ComponentResolver} from '@angular/core';
import {Observable} from 'rxjs/Rx';

@Component({
selector: 'my-app',
template: `
<h2>Above</h2>
<div #putStuffHere></div>
<h2>Below</h2>
`
})
export class AppComponent {
@ViewChild('putStuffHere', {read: ViewContainerRef}) putStuffHere;

constructor(
public view:ViewContainerRef,
public compResolver:ComponentResolver
){}

ngAfterViewInit(){
const url = 'https://gist.githubusercontent.com/johnlindquist/90c0a12814939738809ae0dceacdcf93/raw/e95c3204af1335693a45d65dbb61162824ad5ab8/loadMe.ts';

const importer = url => Observable.fromPromise(System.import(url));
const resolve = comp => Observable.fromPromise(this.compResolver.resolveComponent(comp));

importer(url)
.switchMap(comp => resolve(comp.LoadMe))
.subscribe(factory => this.putStuffHere.createComponent(factory))
}
}

URL里的远程组件

import {Component} from '@angular/core';

@Component({
selector: 'load-me',
template: `<h1>I'm a component loaded from a Gist!</h1>`
})
export class LoadMe{}