我目前正在使用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運行。任何有關在哪裏聲明該變量的建議?
閱讀:https://angular.io/guide/lifecycle-hooks。您必須正確實施生命週期掛鉤才能使其工作。只要將它們添加到沒有正確的'implements'的組件中就行不通。 –
@ R.Richards我在我的代碼中的所有正確位置都有'implements'標記 - 還有什麼想法?我將在 – GravDev1
以上發佈更新後的代碼,我無法重現此行爲。當我使用路由器導航時,生命週期會觸發。 –