2017-02-03 55 views
0

背景Angular2等效ReactDOM.render

开始ReactJS组分的正常方式是:

ReactDOM.render(<MyComponent />, document.getElementById('root')); 

起动Angular2组分的正常方式是:

platformBrowserDynamic().bootstrapModule(MyModule); 

MyModule在'声明'和'引导'下注册了MyComponent。 MyModule也可能包含一些服务。 MyComponent本身定义了HTML选择器。

问题

的Angular2方法调用的一些问题,其中ReactJS方式并不:

  1. 在页面的生命周期之后,你怎么渲染MyComponent的第2个时间上的另一部分这一页?
  2. 如何检索和使用模块中的服务,并只在需要时才呈现MyComponent?

(你的答案,考虑一下,如果它的工作原理之外或angular2执行上下文里面,如果有差别)

回答

0


你不想重用你RootComponent为会导致堆栈溢出异常。这会发生,因为RootComponent(显然)是你的应用程序根目录。将RootComponent放入RootComponent中将导致递归调用,永远不会停止。

2.
不知道如果我误解你在这里,如果我这样做,请评论,我会尝试再次解释。

您可以在RootComponent(以及任何其他属于NgModule的类)中使用任何声明的服务。角度中的每个组件都定义了您可以使用的生命周期钩子(https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html)。比如,你可以使用你的服务之前,如果这就是你所感兴趣的RootComponent已初始化看到这个例子:

import { Component, OnInit } from '@angular/core'; 
import { MyService } from '../Shared/my-service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent implements OnInit { 

    constructor(private _service: MyService) { 
     // This is executed before ngOnInit() 
     this._service.doStuff(); 
    } 

    ngOnInit() { 
     // Here we can do more stuff when the component is "starting" 
     this._service.doMoreStuff(); 
    } 
} 
+0

1.假定你是我乳宁​​它现有的角上下文中。如果我想在未由角度管理的网页的另一部分再次显示它,例如在引导模式中,该怎么办? –

+0

2.你假设我有一个放置组件的地方。如果我想问这个服务是什么,如果它不知道答案,那么请打开一个引导模式并初始化它内部的组件以询问用户的输入? –

+0

顺便说一句,这些都不是人为设想的情况,这些都是实际的用例。 –