Issue with Angular authentication during login attempt

I am a beginner in Angular and I'm using this method to allow users to log into the system.

loginuser(){
    const user = {
      username: this.username,
      password: this.password
    };
    this.Auth.loginUser(user).subscribe((res)=>{
      if(res){
        this.Auth.storeData(res.token, res.user);
        this.flashMessage.show('You are Successfully logged In.', { cssClass: 'alert-success', timeout: 5000 });
        this.router.navigate(['/userProfile']);
      }else{
        this.flashMessage.show('Your Password or Username is Incorrect.', { cssClass: 'alert-success', timeout: 5000 });
        this.router.navigate(['/login']);
      }

    });
  }

However, I encountered an error in my VScode editor which looks like this. https://i.sstatic.net/dNt45.png

Additionally, my angular-cli is showing these errors as well. https://i.sstatic.net/08pvq.png I have clearly defined those parameters in my node function. Here is my node function:

router.post('/login', (req, res)=>{
    const name = req.body.username;
    const password = req.body.password;
    //console.log(password);
    User.findByName(name,(err, user)=>{
        if(err) throw err;
        if(!user){
            res.json({state: false, msg:"No User Found"});
            //return false;
        }
        User.passwordCheck(password,user.password, (err, match)=>{
            if(err) throw err;

            if(match){
                const token = jwt.sign({User} , config.secret, {expiresIn:86400*3});
                res.json({
                    state: true,
                    token: "JWT" + token,
                    user:{
                        id:user._id,
                        name:user.name,
                        ID:user.ID,
                        IDexpDate: user.IDexpDate
                    }
                });    
            }else {
                res.json({state:false,msg:"password does not match"});
            }
        });

    });   
    console.log(password);
});

I am using Angular version 6 for developing this application. I have searched extensively but couldn't find any similar issues. It's possible that my service functions may also need review, so here are my service files:

readonly baseURL ='http://localhost:3000/users/login';    
storeData(token,userdata){
    localStorage.setItem("tokenid",token);
    localStorage.setItem("user",JSON.stringify(userdata));
    this.authtoken = token;
    this.user= userdata
  }
  loginUser(user){
    let header = new HttpHeaders();
    header.append('Content-Type','application/json');

    return this.http.post(this.baseURL,user,{headers:header});
  }

When I console.log res.token and res.user, it gives me values in my console log. My concern is why the VScode editor is showing me errors like that. Thank you very much for taking the time to help me with this.

Answer №1

When defining response types in Node, it does not automatically transfer to TypeScript. You must manually define it.

Referencing resp.user and resp.token in Angular requires you to explicitly declare these objects in your response. By using resp: any, Angular is instructed not to enforce matching types.

If the response always contains a user and token, it is recommended to explicitly declare the response:

resp: {
user: string,
token: string 
}

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

Configuring TypeScript to utilize worker_threads

Currently, I am attempting to implement WebWorkers in my Typescript project and I have encountered a hurdle. Despite having installed @types/node and updating everything, 'worker_threads' has transitioned from an experimental feature to a stable ...

Emphasizing the chosen element in a list using angular

After retrieving an array of items from the database, my list is constantly changing, causing the HTML display to update dynamically. However, I am struggling with highlighting only the selected item in the list, as the entire list gets highlighted upon se ...

Examining form functionalities: angular2 form testing

Currently, I'm facing an issue while attempting to test a component that utilizes 'FormGroup' and 'FormBuilder'. Whenever I run the test file for this particular component, I encounter an error stating that 'FormGroup' an ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Using [(ngModel)] on a field within an object that is nested inside another object

I am facing a challenge as I attempt something that may or may not be feasible. Within an Angular form, I have an object structured like this: export class NewUserRegisterModelDTO{ userData:UserDetailModelDTO; roles:RoleModelDTO[]; ownerData:O ...

The project graph creation for NX has encountered a setback and was unable to be completed. The worker has halted with exit

I've encountered an issue with my Angular project while using nx. Upon running npm install, I received the following error: > NX Nx Daemon was not able to compute the project graph. Log file with the error: ...\node_modules\.cache ...

Tips for adding npm modules in StackBlitz?

Is it possible to install npm packages for Angular on StackBlitz without a terminal? I'd like to know the process. ...

Stepper that is vertical combined with table information

I am currently facing a unique challenge with a component I'm trying to create. It's a combination of a vertical Stepper and a Datagrid. My goal is to group specific table sections within the content of a vertical Stepper, purely for data visual ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

How to customize Material UI Autocomplete options background color

Is there a way to change the background color of the dropdown options in my Material UI Autocomplete component? I've checked out some resources, but they only explain how to use the renderOption prop to modify the option text itself, resulting in a a ...

Can you identify the type of component that is returned from the withStyles() function?

My project includes a simple Dictionary component with basic properties: interface DictionaryProps { word: string; } In another component's props, I am looking for a generic component that only requires a string word: dictionary: React.ComponentC ...

Angular patch value not functioning properly after initial use

Whenever I click on the edit icon, I want the form field to populate. It works correctly the first time, but subsequent clicks on different icons do not update it. However, if I hit the cancel button and then click on any edit button again, it works fine. ...

Tips on implementing pdf-lib in Angular?

I came across the pdf-lib library and am interested in incorporating it into my Angular project. However, I couldn't find any documentation on how to import it specifically for Angular. Can anyone assist me with the process of importing this library ( ...

What is the reason that the protected keyword is not retained for abstract properties in TypeScript?

I'm uncertain whether this issue in TypeScript is a bug or intended functionality. In my Angular project, I have 3 classes - an abstract service, a service that implements the abstract service, and a component that utilizes the implementing service. ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

Encountering an issue in the test file when using react-router-dom v6: "The 'history' property is not found on the 'IntrinsicAttributes & RouterProps' type."

Main script: import { useContext, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; import AuthenticationContext from './AuthenticationContext'; function HandleOAuthCallbackRoute() { co ...

Addressing base-href duplication in subfolders when building with Angular 4

When deploying builds of my Angular app to an S3 bucket, I organize them into different subdirectories based on the branch name. The URLs follow this pattern: pr.example.com/add-cool-spinner pr.example.com/increase-awesomeness If I use --base-href /add-c ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...

Ways to employ data binding for extracting a user-input value and performing multiplication operations with the enclosed {{ ...}} tags

My API response includes the price of a product, which is represented as {{price}} I have a system where I can add or reduce the number of products: <div class="number-input"> <h2>Price: {{price }}</h2> <button oncli ...

Is there a forEach loop supported in Angular2? If so, why does it display all objects with the same value?

Hello everyone, I'm currently facing an issue with getting server response objects and passing them into a new Array object. In the code snippet below, you can see that when I try to print these newly passed objects using a forEach loop, they appear a ...