2017-02-03 99 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

順便說一句,這些都不是人爲設想的情況,這些都是實際的用例。 –