Error message: "Declared app-routing module in Angular 2 is encountering routing declaration

Currently, I am immersing myself in learning Angular 2 through the official tutorial available at https://angular.io/docs/ts/latest/tutorial/toh-pt5.html. However, I have encountered an issue related to routing. The error message displayed states: Type DashboardComponent is part of the declarations of 2 modules: AppRoutingModule and AppModule! I am unsure of where I might have made a mistake as my code seems to align with what is provided in the tutorial.

Error message:

My code:

AppModule

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';

import { AppComponent }         from './app.component';
import { DashboardComponent }   from './dashboard.component';
import { HeroDetailComponent }  from './hero-detail.component';
import { HeroesComponent }      from './heroes.component';
import { HeroService }          from './hero.service';

import { AppRoutingModule }     from './app-routing.module';

@NgModule({
  imports: [
    AppRoutingModule,
    BrowserModule,
    FormsModule,

  ],
  declarations: [
    AppComponent,
    DashboardComponent,
    HeroDetailComponent,
    HeroesComponent
  ],
  providers: [ HeroService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

App-routing Module

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent }   from './dashboard.component';
import { HeroesComponent }      from './heroes.component';
import { HeroDetailComponent }  from './hero-detail.component';

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard',  component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes',     component: HeroesComponent }
];

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

App Component

import {Component} from "@angular/core";

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <nav>
        <a routerLink="/heroes">Heroes</a>
        <a routerLink="/dashboard">Dashboard</a>
    </nav>    
    <router-outlet></router-outlet>`
})
export class AppComponent {
    title = 'Tour of Heroes'
}

Dashboard Component

import {Component} from "@angular/core";
import {Hero} from "./hero";
import {HeroService} from "./hero.service";
import {Router} from "@angular/router";


@Component({
  selector: 'my-dashboard',
  moduleId: module.id,
  templateUrl: `dashboard.component.html`
})
export class DashboardComponent {
    heroes: Hero[] = [];

  constructor(private heroService: HeroService , private  router: Router)
  {

  }
  ngOnInit(): void{
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));

  }
  gotoDetail(hero: Hero): void {
    let link = ['/detail', hero.id];
    this.router.navigate(link);
  }
}

I appreciate any assistance you can provide on this matter.

Answer №1

Encountered the identical issue, which stemmed from a mismatch between the code and angular module versions. While my angular module was RC5 version, I inadvertently utilized the commercial sample code. Simply updating the angular version resolved the issue smoothly.

Answer №2

During my journey through the "Routing" section of the tutorial, I encountered a bug that was surprisingly caused by a missing parenthesis rather than not importing DashboardComponent. It could have been a simple oversight on my part, as the tutorial did not explicitly mention adding that import statement. However, it is possible that others may encounter the same issue without clear instruction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 14 troubleshooting: Issues with using getRawValue() in IndexOf function

In this scenario, I have a straightforward Person interface defined as: import { FormArray, FormControl, FormGroup } from '@angular/forms'; import { Address } from './address'; export class Person { id: FormControl<number>; n ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

When utilizing the Angular library in an Ionic project, make sure to call the inject() function within an injection context

I have been working on a project that involves an angular workspace containing an angular web app and an angular ionic app. In an effort to reuse my existing authentication service, which utilizes AngularFireauth and AngularFirestore, I extracted the servi ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...

How can users create on-click buttons to activate zoom in and zoom out features in a Plotly chart?

I am currently working on an Angular application where I need to implement zoom in and zoom out functionality for a Plotly chart. While the default hoverable mode bar provides this feature, it is not suitable for our specific use case. We require user-cr ...

I'm looking for the Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK. Does anyone know where I can find them and how

Where can I locate Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK and how can I use them? I am utilizing TypeScript for Angular2 and I would like to have the code assistant readily available when implementing "AWS Cognito." While I al ...

Is there a way to automatically determine the parameters of a constructor to match the default class type in TypeScript

I need a function in a class that can utilize a type from constructor arguments, but I am unsure how to achieve this. class CustomClass<Type1, Type2=any>{ a: string = 'a' constructor(private readonly parameters: { attributes: Type ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Eliminate the "Potential 'undefined' Object" error without resorting to non-null assertion or optional chaining

Below is the code snippet I am working with: export type ConditionalItemType = [ { condition: string }, { [key: string]: FormItemDataType } ]; export type ConditionalItemDataType = ConditionalItemType[]; export type FormItemDataType = { required: bo ...

Utilize @agm/core in Angular 6 to load Google Maps by first retrieving latitude and longitude data from the server

I am currently developing a project in Angular6 that involves utilizing the "AGM - Angular Google Maps" library for mapping functionalities. One of the requirements is to dynamically draw the map based on latitude and longitude data fetched from the serve ...

Should we use fakeAsync() or done() to handle asynchronous tasks

When creating an Angular test with Jest and dealing with asynchronous operations, do you have a preference for how to handle it? it('', fakeAsync(() => { // test code here })); or would you rather use something like it('' ...

Mastering the art of debugging feathersjs with typescript on VS Code

I am facing an issue while trying to debug a TypeScript project with FeathersJS using VSCode. Whenever I try to launch the program, I encounter the following error: "Cannot start the program '[project_path]/src/index.ts' as the corresponding J ...

Guide on assigning a class to an array of JSON objects in TypeScript

If I have an array of JSON objects, how can I cast or assign the Report class to it? console.log('jsonBody ' + jsonBody); // Output: jsonBody [object Object],[object Object] console.log('jsonBody ' + JSON.stringify(jsonBody)); // Outpu ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

Tips for showcasing an array in nested elements within an Angular mat-tree

I'm new to Angular and I need help displaying an array's values within the child elements of a material tree. Specifically, I want to show the names of fruits (such as Apple, Banana...) in the child elements. The colors and discounts from the ar ...

A data type representing a specific category rather than a specific object

My job involves working with Sequalize models, which are essentially classes. Upon registration, these models are populated with some data that needs to be stored. To accomplish this, I store them in a list. However, when retrieving a model into a variab ...

Angular 15 is unfortunately not compatible with my current data consumption capabilities

I'm currently facing an issue with Angular 15 where I am trying to access the "content" element within a JSON data. However, when attempting to retrieve the variable content, I am unable to view the elements it contains. import { Component, OnInit } ...

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

Is it advisable for a component to handle the states of its sub-components within the ngrx/store framework?

I am currently grappling with the best strategy for managing state in my application. Specifically, whether it makes sense for the parent component to handle the state for two subcomponents. For instance: <div> <subcomponent-one> *ngIf=&qu ...