【问题标题】:router.navigate is not working (Angular6, lazy loading)router.navigate 不工作(Angular6,延迟加载)
【发布时间】: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 以进行重定向,而您的本地代码将不起作用。

标签: angular angular6


【解决方案1】:

我遇到了类似的问题,我是如何解决的:

在 Component.ts 中

constructor(private router: Router, private route: ActivatedRoute){}

this.router.navigate(['../landing'], {relativeTo: this.route})

试试这个,如果有帮助请告诉我!!!

【讨论】:

    【解决方案2】:

    尝试改变这个:

    {
      path: 'login',
      loadChildren: './login/login.module#LoginModule'
    }
    

    到这里:

    {
      path: 'login',
      loadChildren: () => LoginModule
    }
    

    【讨论】:

      【解决方案3】:

      但我最好的解决方案是:

      添加到构造函数:

      constructor(private readonly loader: NgModuleFactoryLoader)
      

      那么只有在加载模块本身之后你才应该调用导航:

       this.loader.load(./login/login.module#LoginModule)
                      .then(factory => {
                          this.router.navigate(['/landing']);
                      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        • 1970-01-01
        • 2018-07-19
        • 1970-01-01
        相关资源
        最近更新 更多