This error message is indicating that the 'csrf_token' property cannot be found within the 'Object' type

This is a straightforward query.

I am attempting to set up a login system using Angular 5 for the front end and Drupal 8 for the backend. The connection is established successfully, I can send JSON data to the Drupal site, and it returns a CSRF token to me.

Now, my goal is to save this token in the localstorage.

Below is the login function defined in my login.service.ts file:

login (user: User): Observable<User> {
      const url = `${this.mainUrl}user/login?_format=json`;  
    const loginReturn = this.http.post(url, user, httpHaljson);   
    console.log (loginReturn);    

    return loginReturn 
    .map(user => 
      {
     // store user details and jwt token in local storage to keep user logged in between page refreshes
      localStorage.setItem('currentUser', JSON.stringify(user));
      return user;           
     })   
    .pipe( 
        tap((user: User) => this.log(`Token `+  JSON.stringify(user.csrf_token))),
        catchError(this.handleError<User>('login'))
      );
}

If I try something like this:

.map(user => 
              {
             // store user details and jwt token in local storage to keep user logged in between page refreshes
              localStorage.setItem('currentUser', JSON.stringify(user));
              console.log ('object' + JSON.stringify(user));
              console.log ('CSRF TOKEN' + JSON.stringify(user.csrf_token));
              return user;           
             }) 

The console properly displays the csrf token without any issues, but there's an error message on the console:

Console Output:

object{"current_user":{"uid":"4","name":"cravushedal"},"csrf_token":"lY4vX3Ns_PrBkpPqoit4PEuEhXlimhKJ-xBt6ouUMXc","logout_token":"KOvJljv47rO3tRV3OG37ZKH57VWAG2gGxPe8nwCmN7A"}

login.service.ts:39 ERROR TS2339:
Property 'csrf_token' does not exist on type 'Object'.

The error states: ERROR in src/app/login.service.ts(37,65): error TS2339: Property 'csrf_token' does not exist on type 'Object'. https://i.sstatic.net/s3oyj.png

Answer №1

It has been pointed out in the comments that this issue arises because Typescript is unable to determine the type of your user property.

When you make a call to HttpClient#post without specifying a type, it will return an Observable<Object>. However, Object does not have any defined properties and is not as flexible as any.

To resolve this, you should specify the type for your HttpClient#post call like so, making the return value an Observable<User>:

this.http.post<User>(url, user, httpHaljson); 

If you are using map, you can also specify the actual type like this:

.map((user: User) => ...

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

Exploring the world of sound: utilizing jPlayer to stream audio files stored in

Currently, I am working on a substantial project that involves generating a list of music files for the user. My goal is to use jPlayer to play a file when a specific row is clicked on. Here is the code snippet at the head of the page: $(document).ready( ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Customize div styles according to the website domain

I want to dynamically change the header of my website based on whether it is in dev QA or production environment. Below is the HTML code: <div id="wrapper"> <form id="form1" runat="server"> <div class="wrapper"> <div> ...

Using querySelector() to target specific divs by their classes while excluding any other classes

I am attempting to retrieve only the first divs while excluding the second ones: <div class="_5pcr userContentWrapper"> <div class="_5pcr userContentWrapper _4nef"> After researching, I discovered that the querySelector function should be abl ...

How can I disable the onClick event for an image within a div in an onClick function?

Is there a way to disable click events for an image using its image id? For example, if the id is id12, I want to disable the click event. I attempted to use `unbind` but it appears that it only works if the event is bound using jQuery? ...

Is there a way to find the magnitude of a whole number without relying on the Math.abs function?

Is there a method to obtain the absolute value of a number without utilizing math.abs? Here is my current approach: function absValue(number) { var abs = number * number; return Math.sqrt(abs); } ...

Hovers and click effects for navigating through images

The website I'm currently working on is stipz.50webs.com. p.s. HOME functionality is not active at the moment. Having successfully implemented the onhover and onmouseout features, my next goal is to enhance the navigation effects for each div/img so ...

Dealing with the error: "Error in checking the expression as it has been altered"

I have a dialog form where users can add new projects. I want to prevent the save buttons from being enabled until all required fields are filled in correctly. I have an isValid() function that handles this validation and it appears to be working properly. ...

Cease the form submission process using Ajax when the input field is blank

I have implemented an ajax code that halts the form submission process if any input value is empty and displays a popup alert. However, I am facing an issue where the process continues even after closing the alert popup. How can I ensure that the process ...

Harnessing Spread Syntax with Map and Filter Operations

Recently stumbled upon a fascinating problem that I couldn't wait to share with all of you. Here is the question at hand: [...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7] I managed to successfully solve the initial section up to the fi ...

utilizing regular expressions in TypeScript

I'm currently working with Angular 2 and I have a URL link: www.abcd.com/Computers_Accessories/panache-air-pc/P-coac-20620024815-cat-z.html#newId=P-coac-41130779424?trackId=paym&subTrackId=&infitag=1234 My goal is to remove the portion #newId ...

Determine the quantity of characters available in a contenteditable field

I have implemented a directive that allows me to input editable content inside a tag Recently, I made modifications to include a character counter feature. However, I noticed that when I add line breaks, the character count increases erroneously. https: ...

The AreaChart in Google is displaying incorrect dates on the axis

I have encountered an issue that I am struggling to resolve. I am in the process of creating a Google Area Chart using a JSON response from a server, specifically with date type columns. Below is the JSON data obtained from the server (copy/paste), organi ...

Tips for resolving the error "Cannot use import statement outside a module" in situations where you are unable to specify module type in the package.json file

I've been working on a Create-React-App project using normal JS (.jsx) and not TypeScript. During the process, I needed to make changes to some build files by replacing references to local files with live ones. That's when I came across the npm p ...

What is the best way to extract a portion of a JSON string?

this.on('success', function(file, responseText) { var theID = JSON.stringify(responseText); alert(theID); window.location.href = ('want to put something here'); }); The ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Modify code on click using JavaScript

Here is some code I found for a custom style switcher: I am thinking about integrating it into my bootstrap dropdown button. The current code for the style switcher is as follows: <form id="switchform"> <input type="radio" name="choice" value= ...

Error: Visual Studio unable to locate Firebase node module

After running the command npm install firebase --save in the root of my project folder, a firebase folder was successfully added to my node_modules directory and the packages.json file was updated accordingly. In addition to using typescript, I have an ap ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Challenges with specifying types in a Typescript login function

Currently facing an issue with the login code, where it is meant to authenticate a username and password, retrieve the corresponding hash from the database, compare them, generate a JWT, and send it back to the user: async login(username, password): Promi ...