The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context:

constructor() {
    gapi.load('client:auth2', this.loadGoogleApi);
}


private loadGoogleApi() {

    // Array of API discovery doc URLs for APIs used by the quickstart
    var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];

    // Authorization scopes required by the API; multiple scopes can be
    // included, separated by spaces.
    var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";

    //init google api 
    gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES
    }).then(() => {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(status => this.updateGoogleSigninStatus(status));
        // Handle initial sign in state
        this.updateGoogleSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get())
    });
}

This block of code executes when the service is initialized. Surprisingly, the

status => this.updateGoogleSigninStatus(status)
function call works fine, but there is an issue with the subsequent line where the function seems to be inaccessible. An unusual scoping problem.

Cannot read property 'updateGoogleSigninStatus' of undefined

If I rearrange that line outside of the promise, everything functions correctly.

Answer №1

handleGoogleApi is passed as a callback and must be handled appropriately to ensure that the correct this context is maintained.

This can be achieved in one of two ways:

constructor() {
    this.handleGoogleApi = this.handleGoogleApi.bind(this);
    gapi.load('client:auth2', this.handleGoogleApi);
}


private handleGoogleApi() { ... }

or:

constructor() {
    gapi.load('client:auth2', this.handleGoogleApi);
}

private handleGoogleApi = () => { ... }

The former method is generally preferred for the reasons outlined in this explanation.

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

Retrieving the checked value of a checkbox in Angular instead of a boolean value

Currently I am working on a project using ServiceNow and AngularJS. I am having trouble obtaining the value of a checkbox. Here is the code snippet: $scope.userFavourite = function(favourite){ alert(favourite); } <labe for="tea"& ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

Firestore TimeStamp.fromDate is not based on UTC timing

Does anyone have a solution for persisting UTC Timestamps in Firestore? In my Angular application, when I convert today's date to a Timestamp using the code below, it stores as UTC+2 (due to summer time in Switzerland). import {firebase} from ' ...

Leveraging uninitialized data in Angular

<ul class="todo-list"> <li *ngFor="let todo of todos" [ngClass]="{completed: todo.isDone, editing: todo.editing}" > <div class="view"> <input class="toggle" type="checkbox" [checked]="tod ...

What is the best way to send requests to an API server without directly specifying the URL in the code?

As I work on implementing an app using Angular 2, I find myself needing to make requests to my API server. However, hardcoding the full URL in every request doesn't seem like a good idea since it's likely to change. While researching a solution, ...

Processing HTTP requests routed from Firebase Hosting to Cloud Functions

I'm currently working on integrating data patching with my Firestore database using http. My goal is to achieve this without relying on an external server, by utilizing Firebase Hosting and Functions. Firstly, I set up my Firebase project and importe ...

Exploring the use of Jest for testing delete actions with Redux

I've been working on testing my React + Redux application, specifically trying to figure out how to test my reducer that removes an object from the global state with a click. Here's the code for my reducer: const PeopleReducer = (state:any = init ...

The error message "registerNgModuleType: Uncaught TypeError: Cannot read property 'id' of undefined" indicates that there is an issue

I am facing an issue with my Angular app repository. After cloning the repository, installing the node_module, and running ng serve, I encounter an error. Despite searching for numerous solutions, none seem to be effective. The app is built on Angular 8.1, ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Tips for preventing HTTP calls within chained Angular subscriptionsHere are some strategies to prevent

I am faced with a scenario where I have to call an HTTP service to retrieve data, and then based on that data, I need to immediately make another HTTP request. Typically, I would use pipe along with switchMap to accomplish this task efficiently. However, t ...

Ways to ensure the React prop type matches the value provided when using typescript?

Within my List component, there are 2 props that it takes in: items = an array of items component = a react component The main function of the List component is to iterate over the items and display each item using the specified component. // List ...

How to format dates with month names in various languages using the date pipe

In my HTML code, I have set up the date display like this: <span >{{ item.lastModified | date : 'MMM d, y' }}</span> As a result, the displayed date looks something like Jul 20, 2021. However, when I switch my browser's language ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

Angular 16 - ALERT! FirebaseError: The first argument passed to the collection() function must be either a CollectionReference, a DocumentReference, or FirebaseFirestore

While working on my Angular CRUD project with Firestore integration, I encountered an issue. Whenever I try to add a new object to the database, I receive the following error message: "ERROR FirebaseError: Expected first argument to collection() to be a Co ...

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Zero's JSON Journey

When I make an HTTP request to a JSON server and store the value in a variable, using console.log() displays all the information from the JSON. However, when I try to use interpolation to display this information in the template, it throws the following er ...

Difficulties in Networking Requests Following Event Emitter Notification in an Angular Application

Within my Angular application, a network request is sent to retrieve filtered data based on user-selected filters. The function responsible for handling the filter values and executing the request is outlined as follows: public onFilterReceived(values) { ...

Building a React TypeScript project is successful on Windows, but encounters issues when attempted on a

Currently, I am immersed in a project that involves React TypeScript. Here is the content of the package.json: { "version": "0.1.0", "private": true, "dependencies": { ///... "react": "^16.8.6", "react-scripts-ts": "3.1.0", }, "scri ...