Troubleshooting Routing Issues with Angular 12 in a .NET Core Application

I'm currently following a guide on building a specific project using Angular 10 with .NET Core Web API and SQL Server functionalities. Interestingly, I decided to use Angular 12 in my environment.

The tutorial goes smoothly up until the routing section.

-I've gone ahead and created the ./app/department and ./app/employee directories along with their respective components. The files are present and they show:

<p>department works!</p>

and

<p>employee works!</p>

-Within the ./app folder, I edited app-routing.module.ts to import these components and add them to the routes. Thus, the routing file is aware of my component files and understands that URL+'/employee' should display the employee component, while URL+'/department' should display the department component. This is all I aim to achieve.

import { EmployeeComponent } from './employee/employee.component';
import { DepartmentComponent } from './department/department.component';

const routes: Routes = [
  {path: 'employee', component: EmployeeComponent},
  {path: 'department', compoennt: DepartmentComponent}
];

-In the ./app directory, modifications were made to shared.service.ts to include methods and observables related to URLs. Although I am uncertain how these contribute to the routing functionality I require, endpoints like /api/employee, /api/department, and /api/GetAllDepartmentNames actually function correctly.

export class SharedService {
readonly APIUrl = "http://localhost:5000/api";
readonly PhotoUrl = "http://localhost:5000/Photos";
  constructor(private http:HttpClient) { }

//The department code mirrors the employee code, hence it's omitted for brevity

  getEmpList():Observable<any[]>{
    return this.http.get<any>(this.APIUrl+'/Employee');
  }

  addEmployee(val:any){
    return this.http.post(this.APIUrl+'/Employee',val);
  }

  updateEmployee(val:any){
    return this.http.put(this.APIUrl+'/Employee',val);
  }

  deleteEmployee(val:any){
    return this.http.delete(this.APIUrl+'/Employee/'+val);
  }

  UploadPhoto(val:any){
    return this.http.post(this.APIUrl+'/Employee/SaveFile',val);
  }

  getAllDepartmentNames():Observable<any[]>{
    return this.http.get<any[]>(this.APIUrl+'/Employee/GetAllDepartmentNames');
  }

-Within the./app directory, I updated app.module.ts to import the shared service, HttpClientModule, Forms Module, and Reactive Forms Module. This sets it apart from the standard list of library imports at the beginning of other files.


import { HttpClientModule } from '@angular/common/http';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';


@NgModule({
  declarations: [
    AppComponent,
    DepartmentComponent,
    ShowDepComponent,
    AddEditDepComponent,
    EmployeeComponent,
    ShowEmpComponent,
    AddEditEmpComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [SharedService],
  bootstrap: [AppComponent]
})
export class AppModule { }

-Ultimately, in app.component.html within the main project folder, I added the router outlet tag.

<h2>some text</h2>
<router-outlet></router-outlet>

-After switching back from Visual Studio Code to Visual Studio, running the project displays an issue where I cannot access the contents of ./app/department/department.component.html by navigating to the /department extension on the localhost:5000 location where the project is hosted, or its employee.component.html counterpart (http://localhost:5000/employee).

The error message received is quite simple, stating 'your webpage doesn't work': This localhost page can't be found. No webpage was found for the web address: http://localhost:5000/department HTTP ERROR 404

I have thoroughly reviewed the structure for any punctuation and spelling errors. Most of the queries related to this problem pertain to a different form of routing than what I am implementing, which demands a deeper understanding of these systems beyond my current grasp. Others delve into more detailed route creation based on controllers and actions, something I am still working on.

I am puzzled as to why this routing setup is not functioning properly. It appears to be a straightforward configuration.

Answer №1

Have you tried initiating ng serve? By doing so, the Angular project would be launched and accessible at http://localhost:4200. If this solution does not work for you, consider adjusting your proxy settings with something similar to the following:

{
  "/api/*": {
    "target": "http://localhost:5000",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

This guidance aims to provide some direction based on the issue as I understand it. Hopefully, this points you in the right path.

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

Here's how you can retrieve URL parameters in NextJs, such as `userid/:this_is_a_param`

I'm struggling to retrieve URL parameters using Next.js. I normally do this with Express by getting a :param from the URL like this: users/:userid/ console.log(req.params.userid) All I've been able to do is get the "userid" from the URL like thi ...

The Angular CLI suddenly decided to stop providing me with useful lines (without sourcemaps) in the browser console, but interestingly the terminal continues

I recently noticed a change in my Angular project that is using Angular CLI. Instead of receiving error lines from my code, I am getting errors from compiled files like main.js and vendor.js. The 'normal' error messages in my terminal are pointin ...

Error while conducting unit testing: Element 'X' is unrecognized

While running the command npm run test, I encountered a specific error in my terminal: 1. If 'app-general-screen' is an Angular component, then verify that it is a part of an @NgModule where this component is declared. 2. If 'app-general-sc ...

Issues with loading SourceMap in DevTools after upgrading from Bootstrap 3 to 4

I am currently working on a project with Angular 6 and .NET MVC where I am in the process of upgrading from Bootstrap 3 to Bootstrap 4. Initially, I had been using the Bootstrap 3 CDN and everything was working smoothly. However, I recently had to switch t ...

Authorizer custom is not being triggered for websocket connection event

I'm currently working on implementing a custom authorizer for an API Gateway Websocket API. Below is my custom authorizer implementation using CDK: const authFunc = new lambda.Function(scope, utils.prefixed("WebsocketAuth"), { runtime: ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

React Material Select: The error is caused by the property 'renderValue' with an expected type, as declared within the 'IntrinsicAttributes & SelectProps' type

Encountering an error with React Material Select, specifically on the Render Value function. How can I resolve this issue while using TypeScript? What should be added to the renderValue line? Error: Type '(selected: Array<number>) => string& ...

Attempting to render the application results in an error message stating: "Actions must be plain objects. Custom middleware should be used for asynchronous actions."

I am experiencing an issue while testing my vite + typescript + redux application to render the App component using vitest for testing. I am utilizing redux@toolkit and encountering a problem when trying to implement async thunk in the app component: Error ...

What methods can be utilized to extend the duration of ngxtoastr's display time?

Is there a way to extend the display duration of ngx-toastr notifications when using toastr.success for success messages fetched from an API? this.toastr.success(this.successMessage); ...

Retrieve the key from the datalist within Form.Control

Upon receiving data from the API in JSON format, I am presented with a list of staff members: const MOCK_STAFF = [{ id: 1, name: "John Doe", department: "HR" }, { id: 2, name: "Jane Doe", department: "Research" }, etc Subsequently ...

Error! Unexpected closure occurred while creating an Angular CLI project with npm

After cloning an Angular (4+) CLI project onto a new machine and running npm install, I encountered an error that reads as follows. This project works perfectly fine on other computers: npm ERR! premature close npm ERR! A complete log of this run can be ...

I'm in the process of putting together a node.js project using typescript, but I'm a little unsure about the steps needed to

Currently, I am working on a node.js project that involves compiling with typescript. I recently realized that there is a directory named scripts dedicated to running various tasks outside of the server context, such as seed file operations. With files now ...

The child_process module in Typescript is unable to recognize execSync as a valid function and returns

Currently, I am attempting to utilize the execSync function from the child_process module. However, after importing the module: /// <reference path="../../../../GENERAL/d.ts/node/node.d.ts" /> var execSync = require("child_process").execSync; Upon ...

What could be causing the node inspector to fail to launch when using nodemon and ts-node together?

I have a basic node server set up in typescript. The configuration in my package.json file looks like this: "scripts": { "build": "tsc", "dev": "nodemon --watch src/**/* -e ts,json --exec ts-node ./src/server.ts", "debug": "nodemon --verbose --wat ...

What is the reason behind the term "interpolation" for the double curly braces in Angular/

Even after over a year of experience with Angular/JS, I find myself struggling to truly grasp the concept of interpolation (for example, {{1+4}}). Can you explain the origin of this term in the context of Angular/JS and if it shares any similarities with ...

Here is a unique version: "Dealing with Node.js ES6 (ESM) Modules in TypeScript can be tricky, especially when the TypeScript Compiler (TSC) fails to emit the

I am facing an issue while transpiling my TypeScript project to JavaScript. I have set the project to resolve as an ES6 Module (ESM) by using the "module":"ES6" configuration, but the problem persists. This is the current setup in my ...

The issue with transferring state does not seem to be resolved in Angular 17, causing problems with APIs being accessed

During my project, I successfully implemented SSR and the transfer state feature on Angular 15 version. The APIs were called from the server side without any issues. However, when I migrated to Angular 17, I encountered a problem where the transfer state n ...

Is it possible to perform sorting and searching of data directly on the client side using AG-Grid?

We have set up an API in .NET Core C# to retrieve data and display it in a grid using AG Grid in Angular. Our API incorporates server-side pagination for efficient data loading. Next, I am looking to add client-side sorting and searching functionalities t ...

The alertController will only appear on the original page where it was first activated

I am facing a peculiar issue with the alertController in my Ionic application. Let me explain the problem and then provide the relevant code snippets. In my Ionic app with tabs, I encounter an issue where alerts are not showing up correctly. For example, ...