【发布时间】:2018-10-29 01:35:55
【问题描述】:
我是 Angular 4+(目前使用 v.6)的新手。我一直在尝试使用 this.router.navigate(['/landing']) 功能从登录组件重定向到登陆组件,它无法正常工作。 它将显示登录页面一秒钟,然后再次重定向回登录页面。
但是,例如,如果我尝试通过普通链接导航,
<a routerLink="/landing">landing</a>
它工作正常。
这是我的 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 { }
这是登录组件中的代码,
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
}
login(){
this.router.navigate(['/landing']);
}
}
这是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 { }
感谢您的帮助。
【问题讨论】:
-
你有护卫吗?
-
@David 不,我不知道。这是一个刚刚创建的干净项目。
-
试试这个,在landing-routing.module.ts,
path:'landing', component: LandingComponent -
在登录 html 组件中,您确定没有
href="#"来调用login()吗? -
你能在这里分享proxy.conf吗?还可能发生的是您的 proxy.conf 可能正在加载 diff main.js 以进行重定向,而您的本地代码将不起作用。