Making an Angular POST request and then navigating to a new component

Hello, I am a beginner in Angular and struggling to make my code work. It seems like a basic functionality issue that I can't seem to figure out.

My goal is to send a post request to my .NET core API to register a user, and once that is done, navigate to a new component prompting the user to check their inbox for email confirmation.

Here is the code I have:

Component:

  navigateToConfirm(): void {
    this.router.navigate(['/confirm-email']);
  }

  Register(): void {
    this.authenticationService.register(this.userid, this.email, this.password).then(this.navigateToConfirm);
}

Service:

public register(userId: string, email: string, password: string): Promise<GuestUser> {
    const url = `${environment.apiHost}api/User/Register`;
    return this.http.post<any>(url, { userId, email, password }).toPromise();
  }

Component I'm trying to navigate to:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-confirm-email',
  templateUrl: './confirm-email.component.html',
  styleUrls: ['./confirm-email.component.css']
})
export class ConfirmEmailComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

}

API endpoint :

[HttpPost()]
[ResponseCache(Duration = 1)]
[AllowAnonymous]
[Route("Register")]
public async Task<IActionResult> Register(RegisterModel model)
{
    var newUser = new GuestUser
    {
        UserName = model.UserId,
        Email = model.Email,
        Password = model.Password,
      
    };

    var result = await UserManager.CreateAsync(newUser, model.Password);

    if (result.Succeeded)
    {
        var token = await UserManager.GenerateEmailConfirmationTokenAsync(newUser);

        byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(token);
        var tokenEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);

        var link = Url.Action(nameof(VerifyEmail), "User", new { email = newUser.Email, tokenEncoded }, Request.Scheme, Request.Host.ToString());

        MailRequest request = new MailRequest
        {
            ToEmail = newUser.Email,
            Subject = "Email Verification",
            Body = $"<h2>Thank you for registering, click the link below to verify your email! </ h2 >{link}>Verify Email</a>"
        };

        try
        {
            await MailService.SendEmailAsync(request);
            return Ok();
        }
        catch
        {
            return BadRequest();
        }

    }

    return BadRequest(); 
}

App-routing-module:

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

    ter';
    import { LoginComponent } from './login/login.component';
    import { QuestionnaireComponent } from './questionnaire/questionnaire.component';
    import { GeneralAdviceComponent } from './general-advice/general-advice.component';
    import { AuthGuard } from './auth/auth.gaurd';
    import { ContactTraceComponent } from './contact-trace/contact-trace.component';
    import { HomeComponent } from './home/home.component';
    import { RegisterComponent } from './register/register.component';
    import { ConfirmEmailComponent } from './confirm-email/confirm-email.component'
    
    const routes: Routes = [
      {
        path: 'login',
        component: LoginComponent
      },
      {
        path: 'general-advice',
        canActivate: [AuthGuard],
        component: GeneralAdviceComponent
      },
      {
        path: 'questions',
        canActivate: [AuthGuard],
        component: QuestionnaireComponent
      },
      {
        path: 'home',
        canActivate: [AuthGuard],
        component: HomeComponent
      },
      {
        path: 'contact',
        canActivate: [AuthGuard],
        component: ContactTraceComponent
      },
      {
        path: '',
        canActivate: [AuthGuard],
        component: HomeComponent
      },
      {
        path: 'register',
        component: RegisterComponent
      },
      {
        path: 'confirm-email',
        component: ConfirmEmailComponent
      },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }

Answer №1

It appears that there is a missing pair of parentheses in the .then() section of the promise, resulting in the failure to invoke the navigateToConfirm method:

    this.authenticationService.register(this.userid, this.email,this.password)
      .then(this.navigateToConfirm())}

Answer №2

It seems like everything is fine with your code, but the issue might be with the register request not working properly. To ensure the request is successful, consider using catch() after then().

For example:

this.authenticationService.register(payload)
    .then(this.navigateToConfirm)
    .catch(console.log)

Update:

You can also try using router.navigateByUrl(path) and updating your method as shown below:

navigateToConfirm(): void {
   this.router.navigateByUrl('confirm-email');
}

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

Tips for managing server data and dynamically binding values in Ionic 3

I am struggling with handling data retrieved from the server. I have a provider that fetches the data through HTTP, and I want to ensure the data is loaded before the page loads. However, there is a delay in reflecting the data on the page. Can someone pro ...

Tips for dynamically updating the Header name based on backend data

I am currently utilizing ag-grid within my Angular application. Within the columnDefs array, I have defined headers for my grid. One of the headers is for a column labeled Amount. My goal is to make this header dynamic, so that if the currency value coming ...

Processing dates with NestJS

I am trying to format a date string in my NestJS API from 'YYYY-mm-dd' to 'dd-mm-YYYY', or even better, into a date object. Unfortunately, the NestJS framework does not seem to recognize when Angular sends a Date as well. Should I be se ...

An error has occurred during the Next.js build process: ReferenceError - The component is not defined

Encountering an error during the yarn build process, but no issues with yarn dev My Typography component is custom-made, and I utilize absolute imports with the baseUrl option in tsconfig.json next version: v9.5.2, typescript version: 3.9.7 See error ou ...

Tips for launching Nx serve in debug mode for Angular using VSCode

When running my Angular Nx project in the VSCode debugger, I encounter an issue with using yarn. yarn start successfully executes the nx serve command when run from a terminal. However, the same yarn start command fails when executed through VSCode debug ...

My app is having trouble updating routes correctly. Can anyone provide guidance on how to configure routeConfig properly for my application?

I'm facing an issue with my angular 2 typescript app component routes not working properly. Whenever I try to change the route to login in the address bar, it fails to load the corresponding HTML content. Strangely, there are no console errors displa ...

Angular 5's recursive directives in dynamic modules without any circular dependencies

I've been experimenting with loading dynamic templates into my Angular 5 app. My first attempt was following the examples in the official Angular documentation, but I quickly realized that they only cover loading static components dynamically. Next, ...

Access to this feature is restricted when using a decorator in TypeScript with NodeJS

I have designed a decorator to handle async errors, but I am encountering difficulties in accessing it within class methods. My goal is to develop a reusable CRUD class that other classes can inherit from, with a method for CRUD operations. Decorator Code ...

Calculate the date input in Angular 7 by subtracting calendar days

As a user of this Angular 7 application, you are required to choose a date from a calendar input and then determine what day it was 40 days ago. Unfortunately, I have not been able to accomplish this in Typescript yet. There are numerous JavaScript solutio ...

Facing issue with Angular 17 where pipe is displaying empty data

I am currently utilizing Angular 17 with the code provided below: database.component.html @for(user of (users | userPipe:filters); track user.id) { <tr id="{{ user.id }}"> <td>{{ user.name }}</td> <td> ...

Utilizing Typescript to pass props to a material-ui button enclosed in styled-components

After setting up my react project using the typescript template, I decided to style the material-ui Button component using the 'styled' method from the styled-components library as shown below: import React from 'react'; import styled f ...

Component remains populated even after values have been reset

My child component is structured as shown below, ChildComponent.html <div> <button type="button" data-toggle="dropdown" aria-haspopup="true" (click)="toggleDropdown()"> {{ selectedItemName }} <span></span> </but ...

Is it possible for me to generate typing/declaration (.d.ts) and decorator metadata (.metadata.json) files with the help of @ngtools/webpack?

Currently, I am in the process of updating an Angular library to be compatible with AOT compilation. To achieve this, I have set up some gulp tasks using ngc. However, I am considering switching to @ngtools/webpack as it provides a more convenient way fo ...

Is it necessary to separate Lodash orderby functions to ensure they function correctly?

For some reason, I'm having trouble sorting my data using lodash in my front-end client code. All the examples I've come across don't involve working with data in an interface, so I can't figure out where I'm going wrong. Let&apo ...

Position the mat-icon button in the top right corner for the close button

I'm struggling with positioning my close icon button at the top right corner of my dialog box. Here is my app-iconbutton component: <button mat-icon-button class="iconbutton" [ngStyle]="{ 'background-color': back ...

Having trouble with the npm install command for setting up the Angular dual list box feature

I attempted to run the npm i angular-dual-listbox --save command, but encountered numerous errors indicating version discrepancies despite having version 8.2.14. I referred to this article: npmjs. The error log is as shown below: C:\GUNEET KAUR\P ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

When you find that the plugins on pub.dev do not offer web support, consider utilizing npm packages for Flutter web development

I am currently working on developing a cross-platform app using Flutter for iOS, Android, and web. However, some plugins do not support web. Fortunately, I came across npm packages that provide the same functionality and I am considering integrating them. ...

The 'ngModel' property cannot be bound to a 'textarea' element because it is not recognized as a valid property

When I run Karma with Jasmine tests, I encounter the following error message: The issue is that 'ngModel' cannot be bound since it is not recognized as a property of 'textarea'. Even though I have imported FormsModule into my app.modu ...

Adding Images Using Angular 8

I'm encountering difficulties with image upload in the file located at '../src/app/assets/'. Below is the Form I am using: <form [formGroup]="formRegister" novalidate=""> <div class="form-group"> <label for="ex ...