Tips for navigating to a new page on click while upholding the Single Page Application concept

Within my Angular project, I have set up the main component to showcase information about various companies in a table.

Beneath this table lies a button that, when clicked, navigates the user to a page containing input fields to add a new company. Once all necessary details are provided, clicking Submit will result in the addition of the new company to the database.

However, an issue arises: How can we redirect the user back to the main component without disrupting the Single Page Application principle?

public addCompany(newCompanyName:String, newCompanyPassword:String, newCompanyEmail:String){
    let newP:any = {
      "name": newCompanyName,
      "password": newCompanyPassword,
      "email": newCompanyEmail,
      "coupons": []
    }

     this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", newP).subscribe(
       (res)=>{
         console.log("new company");
         // How to redirect to adminComponent?
        },
       (err)=>{console.log(err)}
     ); 
  }

I utilize angular routes:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { AdminComponent } from './admin/admin.component';
import { AddCompanyComponent } from './add-company/add-company.component';

const routes: Routes = [
{path:"login", component: LoginComponent},
{path:"admin", component: AdminComponent},
{path:"addCompany", component: AddCompanyComponent}];

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

Desire to transition from addCompany to Admin from within addCompany.

The addCompany function does not execute immediately upon button press; another function (located within addCompany's TS) is triggered first and subsequently calls the addCompany function after validating the fields are not empty.

Error message :

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", ok: false, ...}
error: {error: SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt..., text: "A new customer was inserted"}
headers: HttpHeaders
lazyInit: ƒ ()
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany"
__proto__: HttpResponseBase

Answer №1

To go to another component, use the following code snippet:

this.router.navigate(["/anotherComponent"])
.

Include the following import statement:

import { Router } from "@angular/router";

In your constructor, inject the Router dependency and define a method like this:


constructor(private router: Router) {}

public addCompany(newCompanyName:String, newCompanyPassword:String, newCompanyEmail:String ){
    let newP:any ={
      "name": newCompanyName,
      "password": newCompanyPassword,
      "email": newCompanyEmail,
      "coupons": []
      }

     this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", newP).subscribe(
       (res)=>{
         console.log("new company");
         this.router.navigate(["/admin"]);
        },
       (err)=>{console.log(err)}
     ); 
  }

Answer №2

The reason for the error is that your request object does not match the expected format of your database. To resolve this issue, please consider the following steps:

....
this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", JSON.stringify(newP)).subscribe(
.....

Once you receive the correct response:

(res)=>{
     console.log("new company");
     this.router.navigate(["/admin"]);
    }

I recommend performing an atomic test by trying to navigate to another page without making the request.

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

Navigating through HTML code - a beginner's guide

I have a variable containing the following HTML code: let htmlDocument = '<div id="buildings-wrapper"> \ <div id="building-info"> \ <h2><span class="field-content">Britney Spears' House</span></ ...

Obtaining the interface for a Typegoose class model

I am currently exploring how to create an abstraction for Mongo model functions and looking into ways to reuse the model interface from a typegoose class. My goal is to have a function like this: import CountryModel, { Country } from '../../models/ ...

TS2403 error occurs when an unexported variable with an identical name is utilized in multiple files

As a newbie in the world of TypeScript, I am venturing into creating a backend with Node.js (or should I say Node.ts?). Currently, I am in the early stages of setting up my server and exploring the fundamentals. My setup includes ts-node version 8.6.2 and ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

Retrieve and showcase data using Ionic 2's local storage functionality

Hi, I'm having trouble accessing my data in local storage. Every time I try, it gives me an error. I need assistance with displaying my data at home. Thank you for your help :) Error: Typescript Error Argument of type 'Promise' is not assi ...

How to switch from Bootstrap 4 to Bootstrap 3.3 in an Angular project

As I embarked on my quest for answers, seeking out the necessary precautions for downgrading, I stumbled upon an interesting comparison. Bootstrap 3 boasts a 4-scope grid system, whereas Bootstrap 4 offers a 5-scope grid system. [xs,sm,md,lg,xl] The offs ...

Issue: npm encountered an error due to writing after reaching the end

I've encountered a problem while trying to install Cordova and Ionic. Due to what appears to be a corrupted installation, I had to uninstall NodeJS - Cordova - Ionic. After re-installing NodeJS successfully, the trouble began when running the pop ...

"Can you guide me on how to deactivate the template tab feature in compodoc

I was in need of a documentation generator tool for my Angular 2 application and came across compodoc which proved to be quite helpful for me. When using this tool, I noticed that in the component section, I did not want to include the source code and tem ...

Angular 2 - Dynamically assign Bootstrap class based on specified string parameter

I am currently facing a challenge and seeking guidance. I have data coming in from the server that is displayed in a table format. One of the fields contains string values such as 'OK', 'ERROR', or 'CANCEL'. Is it possible to ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Error arises when attempting to pass interface props to a component in a React Typescript application

I am currently delving into the world of React js and typescript. As part of my learning process, I have created a demo application that allows users to input their name and age. The app features an ErrorModal that should pop up on the screen whenever inco ...

Is it possible that multiple identical queries are being executed in succession when adjusting the amount of data being displayed?

Why do multiple identical GET requests get executed when changing the data amount? [HPM] GET /api/users/get_all?search=&order=asc&pageSize=25&page=1 -> http://localhost:5000 GET /api/users/get_all?search=&order=asc&pageSize=2 ...

Getting an error message with npm and Typescript that says: "Import statement cannot be used outside

After developing and publishing a package to npm, the code snippet below represents how it starts: import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; export interface ... export class controlplaneDependencies ...

The inversify middleware is executed a single time

I utilize Inversify for object binding in the following manner: container.applyMiddleware(loggerMiddleware); let module = new ContainerModule((bind: interfaces.Bind) => { bind<Logger>(TYPES.Logger).toConstantValue(logger); bind<ILogger ...

Tell Angular CLI/Webpack to refrain from embedding images under 10Kb in size

When developing an Angular application using Angular CLI, CSS resources such as svg images that are less than 10kb in size will be automatically inline. While this can improve performance, it can pose a challenge for apps with strict Content Security Poli ...

What is the best way to utilize a negative glob pattern?

After our build process completes, we end up with both e2015 and es5 bundles. For example, in the dist directory, you will find files like these: /common-es2015.7765e11579e6bbced8e8.js /common-es5.7765e11579e6bbced8e8.js /custom.js We are trying to set u ...

Importing TypeScript modules dynamically can be achieved without the need for Promises

I find myself in a scenario where the dynamic nature of these commands is crucial to prevent excessive loading of unnecessary code when executing specific command-line tasks. if (diagnostics) { require('./lib/cli-commands/run-diagnostics').run ...

Typescript combined with MongoDB models

One common issue I have encountered involves a method used on my repository: async findByEmail(email: string): Promise<User | null> { const user = await UserModel.findOne({ email }); if(!user) return null; ...

Preventing the continuation of an Observable chain in RXJS based on a specific condition

Exploring a New Approach I am currently venturing into the realm of creating a route guard in Angular2+, utilizing Observables from a shared service that stores the current user's role as a string. The challenge lies in transitioning my thought pro ...

What is the best way to ensure the website theme remains consistent after a refresh in React?

I am currently enhancing a weather forecast website by incorporating a theme toggler feature. The functionality has been successfully implemented, but I am facing an issue where the selected theme does not persist after reloading the page. Can someone he ...