The function is failing to trigger when clicked within an Angular 5 app

Hey everyone, I'm facing a minor issue with my Angular 5 project. I am trying to use a common session check method from a shared TypeScript file. This method is used both when the page loads and when the logout button is clicked to redirect the user to the login page. Strangely, it works fine when the page first loads but throws an error of 'undefined' when the button is clicked. Any help would be greatly appreciated. Thank you!

Dashboard https://i.sstatic.net/wvq1Q.jpg Imported https://i.sstatic.net/92kpK.png

Answer №1

this within the function() { ... } declaration does not refer to your component, but to the function's context. To ensure that the context remains bound to your component, consider using an arrow function:

logout() {
  session.signOut().then(() => {
    this.s.checkIfSignedIn();
  });
}

Additionally, it is recommended to remove the var keyword when declaring a class variable like u.

Some extra tips:

  • Avoid disregarding editor/linter warnings (e.g., to avoid errors when accessing global objects such as gapi, declare them first as shown here: declare const gapi: any;)

  • Maintain proper code indentation for readability

  • Choose descriptive variable names instead of generic ones like a or u to enhance code clarity (consider using existing variables like utils instead of creating new ones)

Answer №2

The declaration is done using var and the call is made using this. Since it's not a component property, it explains why it's not functioning as expected.

Answer №3

When working within a promise, the scope changes.

signOutUser() {
 let self = this;
 var sessionData = gapi.auth2.getAuthInstance();
 sessionData.signOut().then( function() {
   localStorage.clear();
   self.updateSignInStatus();
  });
}

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

Acquire the value of ant-design Select dropdown upon hover

How can we detect the selected option in an ant-design dropdown when it is hovered? <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value=& ...

Ways to automatically update property value in MongoDB once a particular date is reached

Is it feasible to schedule a future date for a document in MongoDB, such as 30 days from the current date, and then automatically update another property of the document when that future date arrives? For instance: creating an event document setting the ...

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

Is there a method to implement retries for inconsistent tests with jest-puppeteer?

Currently, I am struggling with an issue where there is no built-in method to retry flaky tests in Jest. My tech stack includes Jest + TypeScript + Puppeteer. Has anyone else encountered this problem or have any suggestions for possible solutions? I attem ...

Having trouble resolving all parameters for the component xyz: (?, ?) after the upgrade to Angular 2 CLI

After upgrading my Angular2 project from Beta .21 to beta .25.5, which was functioning smoothly, I resolved all errors for both AOT and non-AOT (e.g. ng serve) functionalities. However, upon browser loading, I encountered an error affecting multiple servi ...

"Encountered a roadblock while attempting to utilize the applyMatrix

I am currently working on running an animation using a JSON file and a custom JSON loader, not the one provided with three.js. Within the JSON file, there is an object called frames that contains multiple frames, each with shape information and a simulatio ...

Issue with Three.js CanvasRenderer not displaying Mesh when using multiple materials

Encountering an issue with CanvasRenderer not rendering a Mesh that has multiple materials applied to a BoxBufferGeometry. The Mesh appears without any materials when using CanvasRenderer, but works as expected with WebGLRenderer. Check out the example co ...

How can I prevent an Angular 2+ app from loading until the APP_INITIALIZER has completed its execution?

While I have managed to call a service before the root component loads, I am struggling to find a way to make the whole app wait until the service completes successfully. Essentially, I am looking for a way to make it a synchronous call. The service is loa ...

In JavaScript, capture data returned from a function in a separate variable using a POST REST API call

So, here's the deal - I've got this awesome code that does a POST to an API in order to fetch some data. The best part? It works like a charm when it's wrapped up neatly in a function. But now, the tricky part comes in. I need to actually re ...

HighCharts.js - Customizing Label Colors Dynamically

Can the label color change along with gauge color changes? You can view my js fiddle here to see the current setup and the desired requirement: http://jsfiddle.net/e76o9otk/735/ dataLabels: { format: '<div style="margin-top: -15.5px; ...

The disappearing act of the Show/Hide Button in Sencha Touch 2.3.1: what's the

I'm running into an issue with my sencha touch app. Here is the container I have defined: { xtype: 'container', text: 'SOMETHING', height: '15%', width: '15%', ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

A method to access a stored value in localStorage that does not involve utilizing the __zone_symbol__value property

I am encountering a problem with localStorage. After storing user information in localStorage, I am unable to retrieve it without using the __zone_symbol__value property of the parsed value. This is how I store data into locaStorage localStorage.setItem(& ...

Merge MathJax into SystemJS compilation

I utilize SystemJS to construct an Angular 2 project and I am interested in incorporating MathJax into a component. To start using it, I executed the following commands: npm install --save-dev mathjax npm install --save @types/mathjax Now, I have success ...

Error occurred in next.js environment file when referencing process.env keys as strings in .env.local file

I have a .env.local file with various values stored in it. NEXT_PUBLIC_GA_ID = myvariablevalue I created a function to validate the presence of these values: export const getEnvValue = (name: string, required = true) => { const value = process.env[na ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

Experiencing difficulty converting a JSON array to a C# list during deserialization

With so many options available for serializing and deserializing JSON, it can be confusing to determine which one is the best choice. It's curious why there are multiple tools that seem to accomplish the same task. Some examples include JsonConvert, J ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...

How can I include a <label></label> in each column header when using Material Table React?

Hey there! I'm currently working on adding a <label></label> to each cell in a table. I'm using Material table, and you can find more information about it here: https://material-table.com/#/docs/features/component-overriding This is ...