简体   繁体   中英

angular routerLink does not work in component with module

I'm trying to use RouterLink but nothing happens.

I have two components, the category and the savecategory. the savecategory is defined in the app.module in the declarations part and the category has its own module. so I'm importing your module into imports

App.module

@NgModule({
  declarations: [
    AppComponent,
    SavecategoriaComponent // <~ savecategory
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpModule,
    HttpClientModule,
    LoginModule,
    CategoriaModule,           // <~~CategoryModule
    NgbModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})

app-routing

const routes: Routes = [
  { path: 'login', component: LoginComponent },  
  { path: 'categoria', component: CategoriaComponent },
  { path: 'categoria/:id', component: CategoriaComponent },
  { path: 'savecategoria', component: SavecategoriaComponent },
  { path: '', pathMatch: 'full', redirectTo: 'login' }
];

Category.module

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    FormsModule,   
    HttpClientModule 
  ],
  declarations: [
    CategoriaComponent
  ]
})

I'm using the following router to go to login screen

<a routerLink="/">Home</a>

works perfectly in the savecategory but not in the category.

Is there any missing import in the category?

The routes array of routes describes how to navigate. Pass it to the RouterModule.forRoot method in the module imports to configure the router.

I included the routes const in the app.module.ts

app.module.ts (excerpt):

import { RouterModule } from '@angular/router';
....

const routes: Routes = [

  { path: 'login', component: LoginComponent },  
  { path: 'categoria', component: CategoriaComponent },
  { path: 'categoria/:id', component: CategoriaComponent },
  { path: 'savecategoria', component: SavecategoriaComponent },
  { path: '', pathMatch: 'full', redirectTo: 'login' }
];

@NgModule({
      declarations: [
        AppComponent,
        SavecategoriaComponent // <~ savecategory
      ],
      imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot(routes), //here for instance add it
        HttpModule,
        HttpClientModule,
        LoginModule,
        CategoriaModule,           // <~~CategoryModule
        NgbModule.forRoot()
      ],
        providers: [],
  bootstrap: [AppComponent]
})

Docs

The Categories Module requires you to import the RouterModule for the 'routerLink' directive to work in your template.

Hope it helps

如果一切顺利,应该可以工作,检查类别模块的路由,很可能没有处理该链接的路由。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM