【问题标题】:Angular 5 navigation from one module component to another module component从一个模块组件到另一个模块组件的 Angular 5 导航
【发布时间】:2018-09-17 15:31:17
【问题描述】:

我在 homeModule 中有 home 组件,在 contactModule 中有 contactUs 组件。

当我在 contactUs 组件中单击取消时,它应该将我们重定向到主页。

路线

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {RouterModule, Routes} from '@angular/router';
import {homeComponent} from './home/home.component';


const routes: Routes = [
{ path: 'home', component: homeComponent},
{ path: 'demo-ui/home', component: homeComponent},
];


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

我尝试了以下代码,但没有成功

 import { Component, OnInit } from '@angular/core';
 import { FormsModule, Validators, NgForm } from '@angular/forms';
 import { Router } from '@angular/router';


 @Component({
   //some code
 })
export class contactUsComponent implements OnInit {
constructor( private router: Router ){
}

ngOnInit() {
}


redirect(){
this.router.navigateByUrl('/home');    }

}
 //html
 <button class="btn btn-primary" type="button"  (click)="redirect()"> 
  Cancel </button>

我也试过了

<button class="btn btn-primary" type="button"  [routerLink]="['/home']"> Cancel </button>

和

<button class="btn btn-primary" type="button"  routerLink="/home"> Cancel </button>

错误:无法匹配任何路由。 URL 段“./home”

【问题讨论】:

  • 希望您已将AppHomeRoutingModule 导入您的AppModule。
  • 是的,我确实在 homeModule 中导入了 AppHomeRoutingModule。我们没有应用程序的通用/共享模块
  • 您是否也将RouterModule 导入到contactModule 中?
  • @ShivangGupta :谢谢我在 contactUs 模块中导入了 AppHomeRoutingModule。它解决了最初的问题。网址已更改,但页面未重定向。任何建议表示赞赏。
  • 你只需要在contactModule中添加RouterModule依赖即可。不需要在 contactModule 中导入 AppHomeRoutingModule。你可以和我共享屏幕。

标签: angular typescript


【解决方案1】:

您需要为routerLink 使用锚标记。

<a class="btn btn-primary" role="button" routerLink="/home">Cancel</a>

【讨论】:

    【解决方案2】:

    在您的 .ts 中创建函数

    像这样:

    redirectToHome(){
       this.router.navigate(['/home']);
    }
    

    并调用您的 html

    <button (click)="redirectToHome()">Cancel</button>
    

    【讨论】:

      【解决方案3】:

      你可以使用这个:this.router.navigate(['home']);

      【讨论】:

      • constructor( private router: Router, privateactivatedRoute: ActivatedRoute) { } 你在构造函数中添加了Router ??
      • 是的,我做到了。 “错误:无法匹配任何路由。URL 段 'home'”这是我收到的错误。我不认为进口有什么问题
      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 2018-07-21
      • 2019-03-02
      • 2020-01-17
      • 2018-10-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多