What is the best approach for handling server-side validation errors in Angular when making an HTTP call?

After following different tutorials, I have created a service that can transmit login details to the backend for validation and processing. Although I am able to generate appropriate error codes based on user input, I find myself wondering what to do next.


export class AuthService {

    constructor(private http: HttpClient) { }

    getUserDetails(email, password){
        // post to API server - return user info if valid

        return this.http.post('http://localhost/api/listee/task_login.php', {
            email,
            password
        }).subscribe(data => {
            console.log(data, 'returned from login attempt')
            var theData: any;
            theData = data;
            if (theData.post_err || theData.email_err)
                console.log('ak;dsfj');
        })
    }
}

The data is sent back to a function within a class... how can I handle the form elements within that scope? I'm looking for a way to trigger error codes in Angular on the appropriate form elements. How do I access them? Should I manually use document.getElementById or is there a more sophisticated approach?

Answer №1

In my opinion, it would be better if getUserDetail was an Observable.

export class AuthService {

constructor(private http: HttpClient) { }

getUserDetails(email, password): Observable<any> {
// Sends a POST request to the API server and returns user information if valid

    return this.http.post('http://localhost/api/listee/task_login.php', {
        email,
        password
        })
       // .subscribe(data => {
       //      console.log(data, 'returned from login attempt')
       //      var theData: any;
       //      theData = data;
       //      if (theData.post_err || theData.email_err)
       //      console.log('ak;dsfj');
       //  })
    }
}

You can subscribe to this method in your component and access the result.

someMethod(): void {
    this.authService.getUserDetails(email,password).subscribe(result => { 
          //Perform actions with the returned result in the component 

    }
}

It's recommended to let the component handle the subscription and any additional logic instead of doing it in the service. The service should focus on one task - getUserDetails - without dealing with error handling and manipulation.

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

Discover the steps to trigger a Bootstrap popup modal when clicking on an anchor link using Angular

I have an Angular application and I would like to display a Bootstrap popup modal when the user clicks on a link in the footer. Here is the Bootstrap modal code: <button type="button" class="btn btn-primary" data-toggle="modal&q ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

Adding a condition to the react-router v6 element: A step-by-step guide

I am currently in the process of updating my project from v5 to v6 of react-router-dom. However, I have encountered an issue. Everything was working fine in v5 <Route path={`${url}/phases/:phaseIndex`}> {(chosenPhase?.type === PhaseTy ...

Guide on integrating Mapbox GL Draw into an Angular 8 project

I'm currently working on an Angular 8 project that utilizes Webpack. My integration of Mapbox GL JS was successful, however, I am facing issues with importing Mabox GL Draw. Here are the versions I am using: "@angular/core": "8.2.14", "mapbox-gl": "^ ...

The TypeScript error "Uncaught ReferenceError: require is not defined" occurs when the

When attempting to export a namespace from one .ts file and import it into another .ts file, I encountered an error: NewMain.ts:2 Uncaught ReferenceError: require is not defined. As someone new to TypeScript, I am still in the learning process. Below is a ...

Troubleshooting problem with fullscreen mode in videojs on Ionic 2 due to StatusBar issue

Utilizing a Component to run video js in an ionic application I am seeking for the application to cover the status bar when clicking fullscreen on the video The code functions only when placed in the 'constructor' section, but fails to work w ...

I'm encountering an issue where the npm install process is getting stuck while attempting to extract the xxxx package

When running the sudo npm install command on my local machine, everything works fine. However, once I pulled the code into an EC2 Ubuntu machine, the npm install process gets stuck at a certain point. The output shows "sill doParallel extract 1103" and I ...

What is the best way to activate a file input element in my component and define the accepted file types at the same time?

My goal is to display a file upload dialog when a specific option is selected from a drop-down menu using ng-select. Each menu option corresponds to different file types, such as PDFs. Initially, I attempted to achieve this directly within the ng-select ta ...

Best practices for using useEffect to fetch data from an API_FETCH in a certain condition

When retrieving state from an API using Zustand within a useEffect function, what is the recommended approach to do so? Currently, my implementation is quite straightforward: export interface ModeState{ modes: Mode[]; fetchModes: () => void; } expo ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Utilizing google.maps.places.Autocomplete within a JHipster application with a modal pop-up feature

I am struggling to make google.maps.places.Autocomplete function properly within a modal in Jhipster 4.6.1 / angular 4.2. The issue lies with the display of results, as the z-index of the .modal seems to be conflicting with the google css, resulting in no ...

Using styled-components to enhance an existing component by adding a new prop for customization of styles

I am currently using styled-components to customize the styling of an existing component, specifically ToggleButton from material ui. However, I want my new component to include an additional property (hasMargin) that will control the style: import {Toggle ...

How can one store the value of a promise or observable in an external variable?

I have thoroughly researched the .then() method and comprehend its functionality. In my current project, it is successfully providing me with the desired value. async getDay() { try { let ref = this.db.getDay(this.dateFirebase); ref.then(o ...

TypeScript failing to correctly deduce the interface from the property

Dealing with TypeScript, I constantly encounter the same "challenge" where I have a list of objects and each object has different properties based on its type. For instance: const widgets = [ {type: 'chart', chartType: 'line'}, {typ ...

Effortlessly control your CSS within extensive Angular 2/4/5 projects

When working in Angular, I typically organize my CSS on a component basis with some global styling in styles.css. However, I'm looking for a better way to easily update CSS in the future. I want to be able to make changes in one place and see them ref ...

The type 'Function' does not contain any construct signatures.ts

Struggling to transition my JS code to TS, specifically with a class called Point2D for handling 2 dimensional points. Encountering an error message stating Type 'Function' has no construct signatures.ts(2351). Any insights on what might be going ...

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 ...

The custom native date adapter is facing compatibility issues following the upgrade of Angular/Material from version 5 to 6

In my Angular 5 application, I had implemented a custom date adapter as follows: import {NativeDateAdapter} from "@angular/material"; import {Injectable} from "@angular/core"; @Injectable() export class CustomDateAdapter extends NativeDateAdapter { ...