An error occurred within Angular 8 while attempting an HTTP post request, as it was unable to access the 'message' property of

After conducting a search on Stack Overflow, I found a similar question that relates to my issue.

Login OTP Component:

    onSubmitValidOTP() {        
      this.authenticationService.ValidOTP(this.fo.OtpControl.value, username, role)
        .pipe(first())
        .subscribe(
          data => {
            console.log(data);            
          },
          error => {
            console.log(error);            
          });
  }

Auth Validate Service:

ValidOTP(OTP, UserName, type) {    
    return this.http.post<any>(`Staff/ValidateOTP`, { OTP, UserName, type })
      .pipe(map(bool => {        
        return bool;
      }));
  }

Staff Controller:

[AllowAnonymous]
        [HttpPost("ValidateOTP")]
        internal IActionResult ValidOTP(string OTP, string UserName, string type)
        {
            bool Result = false;
            if (type == "SuperAdmin")
            {
                Users _Users = _Context.Users.FirstOrDefault(j => j.Username == UserName);
                if (_Users != null)
                {
                    
                }
            }
            else
            {
                Staff _Staff = _Context.Staffs.FirstOrDefault(j => j.Username == UserName);
                if (_Staff != null)
                {
                    
                }
            }
            return Ok(new { Result = Result });
        } 

An error appeared in the chrome developer console.
https://i.sstatic.net/wLllj.png

Update:
Below is the content of my login.ts file

import { AlertService, AuthenticationService } from '../_services';
import { first } from 'rxjs/operators';
@Component({
  templateUrl: './login.html'
})

export class LoginComponent implements OnInit {      
  returnUrl: string;
  constructor(private Router: Router,        
    private route: ActivatedRoute,
    private router: Router,
    private authenticationService: AuthenticationService,    
  ) {
    this.pageSettings.pageEmpty = true;
    if (this.authenticationService.currentUserValue) {
      this.router.navigate(['/']);
    }
  }    

  get f() { return this.loginForm.controls; }  
  onSubmit() {
    this.authenticationService.login(this.f.LoginUserNameControl.value, this.f.PasswordUserNameControl.value)
      .pipe(first())
      .subscribe(
        data => {
          if (data.validIp) {
            this.router.navigate([this.returnUrl]);
          }
          else {
            this.FormSubmitBool = false;
            this.VerifyOTP = true;
          }
        },
        error => {
          console.log(error);
          this.alertService.error(error);
          this.loading = false;
        });
  }    

  ValidOTP(OTP, UserName, type) {    
    return this.http.post<any>(`Staff/ValidateOTP`, { OTP, UserName, type })
      .pipe(map(bool => {        
        return bool;
      }));

This is just a section of my login.ts file that has been trimmed for clarity.

Update 2:
Here is the code snippet from my authentication.service.ts

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { BehaviorSubject, Observable } from 'rxjs';
    import { map } from 'rxjs/operators';
    import { User } from '../_models';
    
    @Injectable({ providedIn: 'root' })
    export class AuthenticationService {
      private currentUserSubject: BehaviorSubject<User>;  
      public currentUser: Observable<User>;
    
      constructor(private http: HttpClient) {
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
      }
    
      public get currentUserValue(): User {
        return this.currentUserSubject.value;
      }
    
      login(username, password) {
{ username, password })
`Users/authenticate`, { username, password })
        return this.http.post<any>(`Staff/authenticate`, { username, password })
          .pipe(map(user => {
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            return user;
          }));
      }
    
      ValidOTP(OTP, UserName, type) {
        return this.http.post<any>(`Staff/ValidateOTP`, { OTP, UserName, type })
          .pipe(map(bool => {        

            return bool;
          }));
      }
    
      logout() {
        // remove user from local storage and set current user to null
        localStorage.removeItem('currentUser');
        this.currentUserSubject.next(null);
      }
    }

Update 3:
The following piece of code displays an error message in the console.

onSubmitValidOTP() {        
    let IsUpdated = this.authenticationService.ValidOTP(this.fo.OtpControl.value, JSON.parse(localStorage.getItem('currentUser')).username, JSON.parse(localStorage.getItem('currentUser')).role)
    if (IsUpdated) {
      console.log(IsUpdated);
      IsUpdated
        .pipe(first())
        .subscribe(
          data => {
            console.log(data);            
          },
          error => {
            console.log(error);            
          });

    }
    else {
      this.InvalidOtp = false;
    }
  }

Answer №1

It appears that you are working with separate projects for Angular and Web API, based on what I can see in your code.

[AllowAnonymous]
[HttpPost("ValidateOTP")]
public IActionResult ValidOTP(string OTP, string UserName, string type)

To resolve the error message you mentioned (404 message for zone.js), please modify internal to public.

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

The synergy between JSDoc and type mapping

I am in search of a comprehensive and reliable source that provides detailed information on how TypeScript's JSDoc interacts with types, their mappings, and modifications. It is widely known that Pick and Omit maintain the original JSDoc: const any: ...

"Would someone be able to advise me on how to correctly reference the PrimeNG AutoCompleteModule within my

I've been developing an application that relies on auto-complete functionality. To begin, I installed some available templates using the dotnet command line tool and then selected a template directory before installing the Angular template. dotnet ne ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Issues with Angular Http Subscribe functionality not functioning as expected

Hello, in my Angular Component, I have the following code in one of my methods: this.http.get("http://localhost:8080/poeples") .map( resp => { resp = resp.json(); } ).subscribe( (data) => { this.poeples = data; }, err => console.log( ...

Instructions for transferring an Angular / Node.js application to a different computer

Hey there! I'm in the process of transferring my project to a new computer. Just to let you know, I've already set up node.js and mongoDB on the new machine. When it comes to the Angular app, I understand that I need to copy over the frontEnd d ...

Retrieving data through an Angular Material Table by employing an HTTP GET request

I am working with an Angular Material table and need to retrieve data from a service. Below is the code for the service. import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Message } from '../messag ...

What is the correct way to utilize refetchOnReconnect for a builder.mutation endpoint in @redux/toolkit/query?

I'm having an issue with the Redux refetchOnReconnect option not working even after I have called the setupListener(store.dispatch) in my redux store.tsx file and set refetchOnReconnect=true to the endpoint hook call. store.tsx file 'use client& ...

What are the steps for implementing angular DataTable?

Currently working with Angular 6 and trying to implement an Angular data table, but encountering the following error. Need assistance in resolving this issue and implementing the Angular data table successfully. Encountering the error shown below: ERROR ...

Error Encountered While Uploading to Firebase Functions: HTTP Error: 400, Mysterious Issue Un

Whilst attempting to deploy the server side of my Angular Universal SSR app to Firebase Functions, I encountered an issue with the error message Upload Error: HTTP Error: 400, Unknown Error. My understanding is that this error commonly occurs when deployi ...

Encountering a npm error related to code coverage and phantomJS during the ELIFECYCLE

Attempting to execute angular jasmine unit tests on a Linux environment is yielding an error. The error message returned is as follows: > ng test --watch=false --code-coverage [32m26 02 2020 02:44:05.933:INFO [karma-server]: [39mKarma v4.1.0 server s ...

Analyzing a Typescript project using SonarQube Scanner on a Mac OS slave in Jenkins: A step-by-step guide

My current task involves examining a TypeScript project on Jenkins using the SonarQube Scanner plugin on a Mac OS slave. Software: Jenkins (version 2.32.1) SonarQube Scanner for Jenkins plug-in (version 2.5) SonarQube Scanner (version 2.8) SSH slave plu ...

Getting the OS version or name on various devices such as mobile phones, tablets, or PCs within an Angular project

Currently working on a project with Angular 9 and looking to retrieve device information including OS name and version. Unfortunately, the ngx-device-detector plugin is not functioning properly on Android versions 8 and below, as well as version 10 and i ...

Unable to associate with 'userID' as it is not a recognizable attribute of 'view-user'

When looking at my template expression, I came across the following: This points to the ViewUserComponent, which includes: @Input() userID; I'm puzzled as to why I'm encountering this error: Can't bind to 'userID' since it isn& ...

Understanding Scope in TypeScript

Recently, I developed a sample application in Node.js which utilizes pg-promise to execute queries on a Postgres database. I encapsulated this functionality within a class named PostgresDataAccess. However, I encountered an issue while trying to access t ...

Storing Passport.js Token Locally: Best Practices

Struggling to save the jwt token provided by passport.js in browser localStorage, I am facing challenges with transferring it from the server to the client as it is generated on the server side. If anyone can assist me with setting the server-generated to ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

Observable<Any> Filter

I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...

Tips for sending parameters in Next.js without server-side rendering

I followed the documentation and tried to pass params as instructed here: https://nextjs.org/docs/routing/dynamic-routes However, I encountered a strange issue where the received params are not in string format. How is it possible for them to be in an arr ...

Navigate to component depending on an external query parameter in Angular 2

Is there a way to set up my router so that it redirects based on a specific query string? Let's consider this scenario: the application sends an email for code validation, and I want the user to be directed to a specific component when they click on t ...

Encountering an Issue with Dynamic Imports in Cypress Tests Using Typescript: Error Loading Chunk 1

I've been experimenting with dynamic imports in my Cypress tests, for example using inputModule = await import('../../__tests__/testCases/baseInput'); However, I encountered an issue with the following error message: ChunkLoadError: Loading ...