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

Error encountered while importing AgGridModule in Angular2: Unexpected token

I'm facing an issue while trying to integrate ag-grid into my Angular2 project. Whenever I include AgGridModule in the @NgModule imports, it triggers an error message: (SystemJS) Unexpected token at eval import { AgGridModule } from 'ag-grid-ang ...

Identifying the state type within the scope of TypeScript

For my project involving BMI calculation, I want to store the results in an array within a state and keep them locally. export type BmiContextState = { weight: number | undefined; height:number | undefined; open:boolean|undefined; alert:boo ...

Angular2 - Setting focus on input field during component initialization

Currently, I am working on developing a component in Angular2 (Beta 8) that consists of a textbox and a dropdown. One requirement I have is to automatically set focus on the textbox when the component is loaded or when the dropdown selection changes. Can a ...

What is the process for retrieving information from Sanity?

Having trouble with creating a schema and fetching data from sanity. The console log is showing undefined. Not sure where I went wrong but suspect it's related to the schema creation. Testimonials.tsx interface Props { testimonial: [Testimonial] ...

An error persists in PhpStorm inspection regarding the absence of AppComponent declaration in an Angular module

After creating a new Angular application, I am encountering the issue of getting the error message "X is not declared in any Angular module" on every component, including the automatically generated AppComponent. Despite having the latest version of the An ...

Unable to render ASP.NET Core 2 WebAPI and Angular application on the webpage

Following a tutorial, I created an ASP.NET Core 2 Web API. The API functions properly when accessed through the browser at: https://localhost;44313/api/liveconsole To design the Angular UI for my web API, I referred to another tutorial. After multiple at ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Steps for adding a checkbox to an alertController in Ionic 4

Currently, I am working on Ionic 4 and my goal is to create a checkbox field within the Alert Controller that pulls its options from an array of objects. However, when implementing the code, I am only able to see one checkbox instead of having multiple che ...

Event-Propagation in Angular 5 with mat-expansion-panel within another component

In my project, I am facing a challenge where I need to create multiple mat-expansion-panels within one mat-expansion-panel. Everything works fine except for the issue that when I try to open a child-panel, it triggers the close-event of the parent-panel. ...

Issue: Unable to locate module: Error: The system is unable to find the src/app/app.component.css file?ngResource Angular

I am encountering three issues that I cannot seem to pinpoint the mistakes. Error: Module not found: Error: Unable to locate 'C:/Users/DexSh/desktop/C# Angular/Testing/src/app/app.component.css?ngResource' in 'C:\Users\DexSh\ ...

Angular 4 - Issues with route configurations

My Angular application is running smoothly on localhost:4200 using ng serve. The node server can be found at localhost:3000. After running ng build, a bundle file is generated and properly served from localhost:3000 thanks to the line app.use(express.sta ...

Is there a way to dynamically change the options in a dropdown menu using Angular?

I am facing an issue where the values in my dropdown list are changing to null when I click on the form. The add function is working correctly, but this update problem is bothering me. Can anyone provide assistance? Below is the snippet of my HTML code: ...

Having trouble achieving success with browser.addcommand() in webdriverIO using typescript

I tried implementing custom commands in TypeScript based on the WebdriverIO documentation, but unfortunately, I wasn't able to get it working. my ts.confg { "compilerOptions": { "baseUrl": ".", "paths": { "*": [ "./*" ], ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

Having Trouble with React, TypeScript, and MUI Tabs? Dealing with Overload Errors?

Currently, I'm in the process of building a component using MUI Tabs. Here's a snippet of my code: <Box> <Tabs value={value} onChange={handleChange} variant='fullWidth'> {RoomTabs.map((tab, index) => ( ...

Setting up a ts-node project with ECMAScript modules. Issue: Unrecognized file extension ".ts"

I am currently in the process of setting up a minimalistic repository that incorporates ts-node and ESM for a project. Despite the existence of previous inquiries on this topic, I have encountered numerous outdated responses. Even recent answers appear to ...

Angular Search Version 2.0

I am facing an issue with my search functionality in Angular 2. When I type into the search box, the search method on the service is not triggered. I believe there might be a simple solution that I am missing. Any assistance would be greatly appreciated. ...

The interaction between Web API, Angular, and the unique MAC Address

My organization currently operates an Application using ASP MVC. However, the application is experiencing slow performance and confusion due to multiple programmers with conflicting ideas. I have taken on the task of refactoring and migrating it to Angular ...