router.navigate 不工作(Angular6,延迟加载) [英] router.navigate is not working (Angular6, lazy loading)
问题描述
我是 Angular 4+ 的新手(目前使用 v.6).我一直在尝试使用 this.router.navigate(['/landing']) 函数从登录组件重定向到登录组件,但它无法正常工作.它将显示登录页面一秒钟,然后再次重定向回登录页面.
I'm a newbie for Angular 4+ (currently using v.6). I've been trying to use this.router.navigate(['/landing']) function to redirect from login component to landing component, it's not working properly. It will show the landing page for a sec then redirect back to login page again.
但是,例如,如果我尝试浏览一个普通链接,
But if I try to navigate through a normal link, for example,
<a routerLink="/landing">landing</a>
它工作正常.
这是我的 app-routing.module.ts
Here is my app-routing.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: 'login',
loadChildren: './login/login.module#LoginModule'
},
{
path: 'landing',
loadChildren: './landing/landing.module#LandingModule'
},
{
path: '',
redirectTo: 'landing',
pathMatch: 'full'
},
{
path: '**',
redirectTo: 'landing',
pathMatch: 'full'
}
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
这是登录组件中的代码,
And here is the code in the login component,
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
}
login(){
this.router.navigate(['/landing']);
}
}
这是landing-routing.module.ts中的代码
Here is the code in landing-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LandingComponent } from './landing.component';
const routes: Routes = [
{
path:'', component: LandingComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LandingRoutingModule { }
感谢您的帮助.
推荐答案
我遇到了类似的问题,我是如何解决的:
I faced similar issue, how I resolved it:
在 Component.ts 中
In Component.ts
constructor(private router: Router, private route: ActivatedRoute){}
this.router.navigate(['../landing'], {relativeTo: this.route})
试试这个,如果有帮助,请告诉我!!!
try this and let me know if it helps!!!
这篇关于router.navigate 不工作(Angular6,延迟加载)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!