Problem encountered while directing to a component within Angular

Here is the overview of my directory structure:

Directory Structure

login.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { ApicontrolService } from 'src/app/service/apicontrol.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  customerid: number;
  Password: string = "";
  response:string="";
  constructor(private router: Router, private formBuilder: FormBuilder, private apiControl:ApicontrolService) { }

  signin: FormGroup = this.formBuilder.group({
    customerId: new FormControl(null, [Validators.required]),
    password: new FormControl(null, [Validators.required])
  });
  
  ngOnInit(): void {
  }
  async login(){
    this.customerid= this.signin.get("customerId")?.value;
    this.Password= this.signin.get("password")?.value;
    let data={customerId: this.customerid, password:this.Password};
    this.apiControl.letin(data).subscribe(res=>{
      this.response=res;
      console.log("response",res)});

    await new Promise(f => setTimeout(f, 1000));

    if(this.response=='SRIRAM'){
      this.router.navigate(['./viewall'], {data:this.response});

      console.log("yes");
    }
    else{
      console.log("no");
    }

    //this.checkthis();
    }
  }

============================================================================================

viewall.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Route, Router } from '@angular/router';

@Component({
  selector: 'app-viewall',
  templateUrl: './viewall.component.html',
  styleUrls: ['./viewall.component.css']
})
export class ViewallComponent implements OnInit {
  Name: string="";

  constructor(private activatedRoute: ActivatedRoute) {
   }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(params=>{
      this.Name=params['data'];
      console.log("Response in viewall", this.Name);
    });
  }

}

============================================================================================

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MatSlider, MatSliderModule } from '@angular/material/slider';
import { MatButtonModule} from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatRippleModule } from '@angular/material/core';

import { LoginComponent } from './components/login/login.component';
import { ViewallComponent } from './components/viewall/viewall.component';
import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { RouterModule, Routes } from '@angular/router';

const routes : Routes =[
  { path: 'components/viewall', component: ViewallComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ViewallComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatSliderModule,
    MatInputModule,
    MatButtonModule,
    MatRippleModule,
    RouterModule.forRoot(routes)
  ],
  providers: [
    HttpClient
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

============================================================================================

Issue

When I attempt to navigate using a button within the login component, an error message appears in the console:

ERROR Error: Uncaught (in promise): Error: NG04002: Cannot match any routes. URL Segment: 'viewall' Error: NG04002: Cannot match any routes. URL Segment: 'viewall'
    at ApplyRedirects.noMatchError (router.mjs:3593:16)
    at router.mjs:3575:28
    at catchError.js:10:39
    at OperatorSubscriber._error (OperatorSubscriber.js:23:21)
    at OperatorSubscriber.error (Subscriber.js:40:18)
    at OperatorSubscriber._error (Subscriber.js:64:30)
    at OperatorSubscriber.error (Subscriber.js:40:18)
    at OperatorSubscriber._error (Subscriber.js:64:30)
    at OperatorSubscriber.error (Subscriber.js:40:18)
    at OperatorSubscriber._error (Subscriber.js:64:30)
    at resolvePromise (zone.js:1211:31)
    at resolvePromise (zone.js:1165:17)
    at zone.js:1278:17
    at _ZoneDelegate.invokeTask (zone.js:406:31)
    at Object.onInvokeTask (core.mjs:26365:33)
    at _ZoneDelegate.invokeTask (zone.js:405:60)
    at Zone.runTask (zone.js:178:47)
    at drainMicroTaskQueue (zone.js:585:35)
    at invokeTask (zone.js:491:21)
    at ZoneTask.invoke (zone.js:476:48)

Can someone provide insight into what might be missing or causing this issue?

I have researched multiple solutions but haven't found a resolution yet.

Answer №1

edit the following line

change this.router.navigate(['./viewall'], {data:this.response});

to

this.router.navigate(['components', 'viewall'], {
      queryParams: { data: this.response }
    });

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 5+ does not have any compatible call signatures for Type Search

Utilizing an addItem function that I found on this site, I encountered the following error message: Error TS2349 (TS) Cannot invoke an expression whose type lacks a call signature. Type 'Search' has no compatible call signatures. Definition o ...

The `ngx-infinite-scroll` feature does not function properly on mobile devices when used in conjunction with the

I'm currently working on an Angular project that utilizes the mat-sidenav layout and routing. I came across an issue when trying to display a list of elements from a database using ngx-infinite-scroll. Following the user guide for ngx-infinite-scroll, ...

The Dilemma of using forRoot() in Angular 2/4+ Shared Modules

After uncovering the treasure that is forRoot() while delving deeper into Angular dependency injection (DI), I find myself pondering on the best practices for its usage. I came across this method when trying to enable a lazy loaded module to access a serv ...

Angular: use an icon in place of text

Consider this scenario where a component.ts file looks like the following: @Input() studentHeader?: BaseStudent; get studentText() { if(this.studentHeader) { return this.studentHeader.nr + ' - ' + this.studen ...

Creating a loader for a specific component in Angular based on the view

Creating a loader for each component view is crucial when loading data from an API. Here is the current structure of my components within my <app-main></app-main>: <app-banner></app-banner> <app-data></app-data> <app ...

Issue with Angular CLI build test: Unable to locate ng2-material

Currently, I am in the process of developing a new Angular 2 application with the Alpha version of Angular-CLI. To enhance its functionality, I have decided to incorporate the ng2-material library. However, in order to make it work effectively, I had to ex ...

What is the best way to define an event binding statement in the Angular code rather than within the template?

Is it possible to define the event binding statement directly in the code (rather than in the template)? I am trying to dynamically create a menu, and while I can achieve this with routes (since they are strings), using event names seems to be more challe ...

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Unable to utilize Stats.js with @angular/cli version 1.4.4

Attempting to utilize @types/stats with @angular/cli following the guidance at https://github.com/angular/angular-cli/wiki/stories-third-party-lib. However, encountering a tslint error when trying to import * as STATS from 'stats.js'. [ts] Modul ...

Executing unit tests in Angular - launch Chrome upon successful build completion (which may take a while)

There are instances where the Angular app takes longer than the default 2-minute timeout for Chrome started by Karma to capture the content. Is there a method to compel Karma to launch Chrome after the build is completed? In my package.json: { "depende ...

The type 'Store<unknown, AnyAction>' is lacking the properties: dispatch, getState, subscribe, and replaceReducer

I have configured the redux store in a public library as follows: import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '@/common/combineReducer'; import { createLogger } from 'redux-logger'; import thunk ...

Tips for designing a search bar using Angular

search : ____________ I am interested in designing a search bar functionality that automatically triggers when the user inputs 8 or more characters. The input text will be stored in a variable, the search bar will be reset, and the backend API will be che ...

Incorrect Angular Routing Component OpeningI am experiencing an issue where

I am facing an issue with lazy loading a module, where it is not correctly displaying the desired component. Even though the route seems correct, it shows a different component instead. https://i.sstatic.net/v4oAB.png Despite specifying the path for "Pus ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

What is the correct way to declare the mongoose _id in a TypeScript interface?

I have a question about utilizing Mongoose and TypeScript using the interface+class+schema approach. When it comes to storing the _id field, what is the best method? I understand that the database stores it as a bson ObjectID. However, I've come acr ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

Attempting to grasp Angular through an online tutorial - currently facing challenges with understanding ViewContainerRef and TemplateRef

I have been successfully learning Angular until I reached the topic of structural directives. In order to understand them, I had to create my own using TemplateRef and ViewContainerRef. The instructor in the course demonstrated it this way: import { Direc ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...

How to adjust the font size and font style for the [pageSizeOption] in mat-paginator

I am having trouble adjusting the font-size of the [pageSizeOptions] in my mat-paginator element in the application. <mat-paginator [pageSizeOptions]="[10, 20, 30]"></mat-paginator> The "10" appears too small compared to the text "items per p ...