How can you verify if a variable is included in an HTTP response?

After successfully creating this authentication service, everything seemed to be running smoothly...

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { Storage } from '@ionic/storage';
import { EnvService } from './env.service';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  isLoggedIn = false;
  token:any;

  constructor(
    private storage:Storage,
    private http: HttpClient,
    private env: EnvService,
  ) { }

  login(email: String, password: String) {

    let formData = {
      usuario    : email,
      senha      : password,
      retsession : true
    }

    return this.http.post(this.env.API_URL+'/login', formData).pipe(
      tap(response => {
        var token = ('jwt' in response) ? response.jwt : null ;
        this.storage.set('token', token)
        .then(
          () => { console.log('Token Stored: ' + token); },
          error => console.error('Error storing item', error)
        );
        this.token = token;
        this.isLoggedIn = true;
        return token;
      }),
    );
  }

}

Unfortunately, despite its functionality, I encountered a compiling error

[ng] ERROR in src/app/services/auth.service.ts(36,52): error TS2339: Property 'jwt' does not exist on type 'never'.

This issue arises when trying to verify the presence of my token within the HTTP response data...

Can anyone guide me on the correct approach to avoid triggering this error?

Answer №1

In order to verify the existence of the token, you may use the following method:

let token = response['jwt'] ? response['jwt'] : null ;

Warm regards

Answer №2

sagat's solution is accurate. Take a look at this example demonstrating how to pass an interface into an http call:

// form-data.interface.ts
export interface FormData {
  username: string;
  password: string;
  rememberSession: boolean;
}

// login-response.interface.ts
export interface LoginResponse {
  token: string;
  // other properties
}

// login.service.ts
login(formData: FormData): Obvservable<LoginResponse> {
  return this.http.post<LoginResponse>(`${this.env.API_URL}/login`, formData);
}

// To implement this in your component (login.component.ts) or state management (login.state.ts)
// use the following code snippet
this.login(formData).subscribe((response) => {
  // handle the response data here
}

Upon sending an http post, you will receive an observable that can be subscribed to. While not necessary in this scenario, pipe and tap achieve similar functionality.

Note: If you anticipate missing values for certain properties in the response, consider using a class instead of an interface:

// login.response.model.ts
export class LoginResponse {
  token: string
  // other properties

  constructor(data: LoginResponse) {
    this.token = (data && data.token) ? data.token : '';
  }
}

This approach guarantees all properties are present on the model, initialized with default values if needed. This helps avoid errors related to missing data fragments.

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 module parsing encountered an error: the usage of 'import' and 'export' is restricted to 'sourceType: module' only (line 3, character 0)

I've been encountering an issue with building a Nextjs application since yesterday without making any changes at this level. Even after reverting the changes, the error persists. Is there anyone who can assist me with this problem? ./node_modules/ty ...

Issue: FlashMessagesService not provided - NullInjectorError

Utilizing Angular 2 flash messages to showcase a message when the user clicks on the logout button has been quite the challenge. Despite adding a provider in navbar.component.ts and conducting various experiments, I still encounter the same error. Outline ...

Type arguments cannot be accepted in untyped function calls.ts(2347)

My user schema in typescript includes the following interface: interface IUser{ name: string; email: string; password: string; isAdmin: boolean; } Check out the user schema below: const UserSchema = new Schema<IUser>( { name: { type ...

What are the steps for creating a custom repository with TypeORM (MongoDB) in NestJS?

One query that arises is regarding the @EntityRepository decorator becoming deprecated in typeorm@^0.3.6. What is now the recommended or TypeScript-friendly approach to creating a custom repository for an entity in NestJS? Previously, a custom repository w ...

Navigating between parent and child states in an Ionic application can be made even

I have set up my ionic app with a ui-router configuration where the locations state acts as the parent for two other states - map and favourites. Additionally, I have a separate state called updates which serves as a detailed page that can be accessed from ...

Navigating with the Angular router and then triggering a reload

Is there a way to reload the app after navigating to a specific route? I am currently using router.navigate to direct users to different routes based on their roles. It's working fine, but I need to reload the page after routing when coming from the ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

Executing ngOnChanges in Angular 2

Within the Child component, there is an input field. Upon triggering the blur event, the value entered into this input field is passed to the AppComponent using an eventEmitter. This new value is then used to update the Key property of the AppComponent. Th ...

Update the mandatory fields in the required interface to extend to another interface, while ensuring that all subfields become

Currently, I have defined 2 interfaces: interface BattleSkills { strength: number; armor: number; magic_resistance: number; health: number; mana: number; intelligence: number; accuracy: number; agility: number; critical_damage: number; } ...

CSS that relies on the presence of a specific class

I'm a CSS novice and I have encountered a scenario where I need to apply a CSS class only when another class is not present. <div class="border-solid p-2 bg-white mt-1 h-fit" [ngClass]="SOME_CONDITION ? 'tile-con ...

Encountering the "TypeError: fetch failed" error message while attempting to utilize @vercel/og in conjunction with Astro

I've been experimenting with the @vercel/og package in order to set up an API route for generating open graph images. As I work with an Astro application, I simply followed the vercel example that is framework agnostic: // api/og.ts import { ImageRes ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

Angular's ngClass directive failed to be applied correctly

I am currently experimenting with the use of [ngClass] in Angular and it appears that it is not being applied as expected. Interestingly, [ngStyle] for similar CSS styles is working without any issues. What could I be doing wrong in this scenario? There ar ...

submitting an angular form and resetting the values afterward

I've implemented the following Angular form and I want to clear the text field after submitting the form. <form #addcheckinform="ngForm" novalidate (ngSubmit)="addcheckinform.form.valid && saveScheduleCheckin(this.che ...

Reading JSON in Spring Boot can sometimes be challenging, especially when faced with errors like "Cannot deserialize value of type `X` from Array value." This error typically occurs when trying to parse an array value

I am facing an issue with sending data from my Angular application to SpringBoot. The problem arises when the server does not receive the correct object that is being sent. Upon checking the console.log output for what is being sent to the server, everyth ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

Eliminate special characters from a string using Protractor

I am currently in the process of writing protractor tests for my angular application. One particular test case that I am working on involves comparing a span value before and after clicking a button. it('Compare dollar values', function () { ...

What is the process for exporting services within a module?

Is there a way to export a service from a module in angular 2? I am looking to import the service into another component without specifying the exact location of the service. I believe it should be the responsibility of the module to handle this. Core.mo ...

Setting the default prefix value for an input field

I have a form with two fields: country code and Phone Number. My requirement is to set the default value of the country code input field to include a plus sign (+), like this: https://i.sstatic.net/Legfq.png Additionally, I need to be able to send thi ...

Issue with Class-based React Component Inheritance: The "render" property cannot be assigned to the identical property in the parent type

I am currently working on a new React Native app with Typescript and I have decided to utilize class based components. So far, I have created two classes: RouteView.tsx export class RouteView extends React.Component { constructor(props: any, private ...