Received an error message stating "variable res is not defined" when attempting to log in using Angular

I am attempting to authenticate using Angular with Spring Security.

My backend is functioning perfectly.

The issue lies within this function responsible for the login:

onFormSubmit(authBody: authBody ) {

    this.authService.login(authBody)
      .subscribe(res => {
        console.log(res);
        if (res.token) {
          localStorage.setItem('token', res.token);
          this.router.navigate(['/menu']);
        }
      }, (err) => {
        console.log(err);
      });
  }

The console.log(res) returns: {username=med, token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtZWQiLCJyb2xlcyI6W10sImlhdCI6MTYzOTA2NzgzOSwiZXhwIjoxNjM5MDcxNDM5fQ.a-DzNNeVRZ6XUPwYnzAk_P_0yFQO5GXwvBds_7RvGs8}

I have been trying to extract the token from this object, but when testing with if(res.token), it returns undefined.

This is my authentication method service:

login(authBody: authBody): Observable<any> {
    console.log(authBody.username);
    return this.http.post(apiUrl + this.aPILogin, authBody ,{responseType: 'text'})
      .pipe(
        tap(_ => this.isLoggedIn = true),
        catchError(this.handleError('login', []))
      );
  }

Any suggestions, please?

Thank you!

Answer №1

By specifying the responseType as text, you are receiving a string from the observable instead of an object.

In order for this to function as intended, there are two steps you must take:

1.- Ensure that the server is returning valid JSON data. (Unfortunately, I am not familiar with Spring so I cannot provide assistance with this).

2.- Omit the responseType attribute (as it defaults to json), allowing the response body to be automatically parsed into an object.

Cheers!

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

Unable to utilize directives that are declared within the app module in child modules when using Angular 6

Currently utilizing Angular 6. I've established a custom directive named StickyPopover by extending NbgPopover and have integrated it into the declaration of app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { ...

received TypeError when using combineLatest

import { combineLatest } from 'rxjs'; const obs1 = getAndCreateObservableOne(); const obs2 = getAndCreateObservableTwo(); console.log('Initial output', obs1, obs2); obs1.subscribe(e => console.log('Second output', e)); o ...

Utilize angular animations for enhancing the interactivity of a component

My Angular 6 page has three different angular components that I want to animate based on a certain condition: <component1 [@componentState]="componentToShow === 0 ? 'active' : 'inactive'"></component1> <component2 [@comp ...

On localhost, Angular 2 route parameters are automatically converted to lowercase, while they stay capitalized on the server

I am currently working on a .NET Angular 2 program that has a route set up like this: <ControllerName>/:id While running it on localhost with IIS Express, the id route parameter automatically gets converted to lowercase in the URL without any addi ...

The Firebase database is experiencing difficulties fetching the data

Having an issue with my component. Struggling to retrieve data from Firebase. Can someone spot the error in the code below? import { Component, OnInit, Input, ViewChild } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable ...

Encountering the error "Cannot access property 'on' of undefined" during Angular unit testing with Karma and Jasmine

Inside my component.ts file, I have a service called 'socketService' that utilizes socket functionality. Within the component, I include the following code: this.socket = this.socketService.getSocketIOConnector(this.data.product) this.socket.on(& ...

Angular 12 - Directing users to different views depending on their roles

In my situation, the Admin role login will be able to access the Home and UserView Component. After logging in, an Admin will automatically be taken to the Home component. On the other hand, the User role login will only have access to the UserView compone ...

Improving an Angular component through refactoring

Here is an Angular component written in Typescript that I am currently working on: export class ItemsComponent implements OnInit { @Input() invoice: Document; @Input() declaration: Document; private invoiceName: string; private declarationName: string; ...

Leveraging JWT for Retrieving User Information

Exploring JWT and the MERN stack, currently working on authenticating users with JWT. I've successfully set up JWT in local storage but now facing the challenge of making a GET query request to my MongoDB using only the JWT token. Is it necessary to a ...

retrieve an object with enum keys that are indexed

I am faced with a situation where I have a collection of interdependent elements, each identified by a unique code (enumeration). My goal is to retrieve the list of elements that depend on a specific element, and then be able to reference them using myElem ...

Template literals in Typescript provide a powerful way to define string templates with

Here is the code I am working with: type CustomType<T extends string = string> = `custom-${T}-type`; const value: CustomType = 'custom-example-type'; The code above functions as expected, but it does not enforce the expected structure. Th ...

Angular 2.0.0 - Simulated File Loader

For my unit testing, I am facing the challenge of mocking the FileUploader class from ng2-file-upload. Can anyone guide me on how to accomplish this? import { FileUploader } from 'ng2-file-upload/ng2-file-upload'; @Component({ selector: &apos ...

The 'subscribe' property is not found in the type 'OperatorFunction<Response, Recipe[]>'

I'm encountering an issue while attempting to retrieve data from firebase "Property 'subscribe' does not exist on type 'OperatorFunction'" Any suggestions on what might be missing here? import { Injectable } from '@angula ...

Having trouble resolving all parameters for AuthService in Angular

Launching my angular app has hit a roadblock with this perplexing error. Despite attempts to troubleshoot by removing the auth service provider and constructor reference from my component, the issue persists. As a novice in angular, I'm struggling to ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Choosing a value type within an interface or object declaration

Is it possible to extract a nested type object from an interface or parent type? interface IFake { button: { height: { dense: number; standard: number; }; }; otherStuff: string; } type Button = Pick<IFake, 'button'& ...

Develop a structured type that encompasses the stationary attributes of an object-oriented class

Provided are the following classes: class EnumerationDTO { designation: string; id: number; } class ExecutionStatusDTO extends EnumerationDTO { static readonly open: ExecutionStatusDTO = { id: 0, designation: 'Open' }; static readonl ...

Endless cycle of NGRX dispatching

I tried creating a simple ngrx project to test the store, but I encountered an infinite loop issue. Even after attempting to mimic other examples that do not have this problem. To begin with, I defined 2 class models as shown below: export interface IBookR ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...