Out of the blue, the error message "this.http is not defined" popped up

Within my LoginProvider, I have implemented a function that handles the login process and returns the session created as a promise.

@Injectable()
export class LoginProvider {

    constructor(public http: HttpClient) { };

    public async login(credentials: ICredentials): Promise<ISession> {

        let url: string = "https:/url/to/login";

        let headers: HttpHeaders = new HttpHeaders()

        let params: HttpParams = new HttpParams()
            .append("username", credentials.id)
            .append("password", credentials.password);

        return new Promise<ISession>((resolve, reject) => {
            this.http.get(url, { headers: headers, params: params }).subscribe((response: ILoginResponse) => {
                // handle response and return session
            }, (error: HttpErrorResponse) => {
                reject(error);
            })
        });
    }
}

The issue arises when attempting to call this method because this.http is somehow undefined. An error message stating ""_this.http is undefined"" is displayed.

I am puzzled as to why http would be undefined within this function. It is declared in the constructor, so it should be accessible for use in this particular function, right?

Answer №1

The use of this within the context of the new Promise refers to the newly created Promise object rather than the LoginProvider instance.

Instead of:

new Promise<ISession>((resolve, reject) => {
    this.http.get(...)
})

You can simply do:

return this.http.get(url, { headers: headers, params: params}).toPromise()
  .then(response => // handle your response here then return your processed result);

(Remember to import 'rxjs/add/operator/toPromise';)

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

Running a service in Angular 2 when the application starts

I have a service that I want to execute when the app initializes using APP_INITIALIZER, but I keep encountering an error. Unhandled Promise rejection: appInits[i] is not a function ; Zone: ; Task: Promise.then ; Value: TypeError: appInits[i] is not a fun ...

Tips on clearing local storage when the browser is closed or a tab is closed in JavaScript, Angular, and React

Is there a way to automatically remove local storage or session storage data when closing the browser? Specifically, how can I delete the local storage details only when closing the final tab of a website with multiple tabs open? I've attempted variou ...

What is the syntax for creating ES6 arrow functions in TypeScript?

Without a doubt, TypeScript is the way to go for JavaScript projects. Its advantages are numerous, but one of the standout features is typed variables. Arrow functions, like the one below, are also fantastic: const arFunc = ({ n, m }) => console.log(`$ ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

Error: The reference 'GetServerSideProps' is being incorrectly used as a type instead of a value. Perhaps you intended to use 'typeof GetServerSideProps' instead?

Index.tsx import Image from 'next/image' import Head from "next/head" import { sanityClient, urlFor } from "../sanity" import Link from 'next/link' import {Collection, address} from '../typings'; import ...

Storing a variety of values within a formControl in Angular

I'm currently working on a form that involves managing an array of quantity materials in TypeScript. These materials can be added or removed from an inventory and are displayed in the HTML using ngFor. My goal is to allow the FormControl to accommodat ...

Waiting for variable to become false using Angular 7 Observable

The observable below highlights the authentication process: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { CookieService } from 'ngx-cookie-service'; import { Observabl ...

How do I convert the ImagePicker type to Base64 in Ionic Capacitor?

I am currently developing an app using Ionic (Angular-based) along with Capacitor Plugins, specifically the Camera Plugin. The main feature I am working on involves allowing users to choose up to 5 images from their gallery. To accomplish this, I have impl ...

Updating Ionic Library for an Existing Project in Ionic 2

Struggling to locate information on the Ionic 2 website. Suppose a project was initiated with Ionic library version 2.0.1. What steps should be followed to upgrade it to Ionic library version 2.1.0? Is there a standard procedure for this update now that ...

Troubleshooting TypeScript issues in an Angular 4 tutorial demo

I recently started working on the Angular tutorial provided on the official website. However, I have encountered an issue that I am struggling to resolve. After using Angular CLI to create the project, I came across the following code in app.component.ts: ...

IE11 is throwing an error due to an unexpected quantifier in the regular expression

I have a string like SHM{GHT} and I need to extract the value from within the curly braces (GHT in this case). I used RegExp successfully to do this, but encountered an issue when testing on Internet Explorer. The page broke and I received an error message ...

Determining the Validity of a Date String in JavaScript

I encountered an issue while attempting to validate a date string using the following code: const isValidDate = (date: any) => { return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date)); } For instance: let dateStr = "some-random-s ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Angular 5 is rendering a div even if there is no content present

I am currently using Angular 5.2 Firestore When using *ngIf isContent else noContent, my goal is to only render an Observable if it contains data. However, I am facing an issue where the logic always renders isContent even when there is no data present. ...

Enhancing the appearance of Angular material form fields

Can anyone help me with implementing this in Angular 12? Here is the code snippet from my HTML file: <mat-form-field style="width: 70px;" [appearance]="somevariable ? 'none' : 'legacy'" > <input matInpu ...

What is the process to enable mandatory validation after a change in input in Angular 4?

Currently, I am working on a project using Angular 4. One of the tasks I need to achieve is validation. <input [(ngModel)]="someModel" required placeholder="some placeholder"/> The validation triggers immediately, but I want it to only trigger aft ...

Bespoke animated angular material tabs

Having an issue with Angular Material tabs. I have managed to remove the "slide" effect, but I can't figure out how to modify or remove the black effect behind my tab. Can anyone offer some assistance? black effect 1 black effect 2 Here is a snippe ...

Utilizing Typescript and RequireJS for Incorporating jqueryui

Recently, I've been encountering issues with getting jQueryUI to function properly. Strangely enough, prior to attempting to integrate jQueryUI, using jQuery alone worked perfectly fine. The current problem I'm facing is receiving a "TypeError: ...

"Using rxjs, a value is delivered within the subscribe function

function createSingleMapService(mapServiceFactory) { return mapServiceFactory.switchSingleMapService().subscribe((service)=>{ return service }) } This snippet is a factory function in Angular that creates a single map service. The 's ...