2017-07-20 65 views
0

我目前正在使用angular-cli項目。但是,在通過router.navigate導航組件加載組件後,運行組件構造函數時,ngOnInit和ngAfterViewInit掛鉤不會激活。Angular-cli生命週期鉤子不在導航中調用

我在這條路線是/login,我要前往/controlpanel

我讀過https://github.com/angular/angular/issues/8012,但遺憾的是沒有幫助,因爲polyfills不影響我的應用程序目前。

的代碼相關的件是下面:

的router.navigate呼叫:

public attachSignin(element) { 
    this.auth2.attachClickHandler(element, {}, (googleUser) => { 
     this.googleAuth.auth2 = this.auth2; 
     this.googleAuth.userProfile = googleUser.getBasicProfile(); 
     this.router.navigate(['/controlpanel']); 
    }); 
    } 

我的路由設置(從下部模塊):

const dataRoutes: Routes = [ 
    { path: 'controlpanel', component: DataHomeComponent }, 
] 
@NgModule({ 
    declarations: [ 
    DataHomeComponent, 
    GravityMapComponent 
    ], 
    imports: [ 
    GlobalModule, 
    RouterModule.forChild(dataRoutes) 
    ], 
    exports: [RouterModule] 
}) 
export class DataModule { } 

主要應用路由文件:

@NgModule({ 
    imports: [ 
    RouterModule.forRoot() 
    ], 
    exports: [RouterModule] 
}) 
export class MainRoutingModule {} 

有關模塊設置的一點需要注意的是,在子模塊中聲明瞭路由。然後將這些子模塊導入主模塊。主路由文件只是聲明RouterModule.forRoot()是根 - 我盡力跟隨在提出的架構:https://angular.io/guide/http

的成分,被稱爲:

import { Component, OnInit } from '@angular/core' 
import gapi from 'gapi' 

@Component({ 
    selector: 'data-home-component', 
    templateUrl: './data-home.component.html', 
    styleUrls: ['./data-home.component.css'], 
}) 
export class DataHomeComponent implements OnInit { 
    public ngOnInit() { 
    console.log("oninit") 
    } 

    public signOut() { 
    gapi.auth2.signOut().then(function() { 
     console.log('User signed out.'); 
    }); 
    } 
} 

更新:當我使用HashLocationStrategy組件生命週期鉤子運行 - 有誰知道是什麼原因造成的?

更新:當我刪除注入的服務時,使用PathLocationStrategy時運行ngOnInit掛鉤。如果組件只是接收單件服務,那麼爲什麼該組件會作爲注入方式返回?

更新:我將DataHomeComponent隔離爲其最基本的形式 - 似乎declare const gapi: any;使用谷歌的API是防止ngOnInit運行。任何有關在哪裏聲明該變量的建議?

+0

閱讀:https://angular.io/guide/lifecycle-hooks。您必須正確實施生命週期掛鉤才能使其工作。只要將它們添加到沒有正確的'implements'的組件中就行不通。 –

+0

@ R.Richards我在我的代碼中的所有正確位置都有'implements'標記 - 還有什麼想法?我將在 – GravDev1

+0

以上發佈更新後的代碼,我無法重現此行爲。當我使用路由器導航時,生命週期會觸發。 –

回答

0

您是否嘗試過以下操作?

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

    constructor (
    ... 
    private zone: NgZone 
){} 

    this.auth2.attachClickHandler(element, {}, (googleUser) => { 
     this.googleAuth.auth2 = this.auth2; 
     this.googleAuth.userProfile = googleUser.getBasicProfile(); 
     this.zone.run(() => { 
      this.router.navigate(['/controlpanel']); 
     }); 
    }); 

我有打電話通過對我的服務gapi.auth2.getAuthInstance()。簽到()承諾處理程序中一個非常類似的問題。在路由完成時,我的ngOnInit方法都不會在組件中調用。通過區域發送它允許再次進入Angular世界,如文件https://angular.io/api/core/NgZone#run所述。

希望它有幫助。

相關問題