Angular2 encountering an unidentified Auth2 Object during logout process

Greetings,

I am currently experiencing an issue with signing out of an auth2 client. Previously, this process functioned correctly until I upgraded my router to comply with new RC requirements. Now, it seems that the auth2 object is being cleared or lost during the transition from signing in to signing out.

Below is the sign out tag in question:

<a role="button" (click)="signOut()" style="padding-left: 30px;">Log out</a>

This tag simply triggers a call to the signOut() function located in navbar.component.ts (refer below)

signOut() {
    var auth2 = this._navigationService.getAuth2();
    auth2.signOut().then(function () {
    });
    console.log('User signed out.');
    sessionStorage.clear();
    localStorage.clear();
    this.router.navigate(['Login'])
    window.location.reload()
}

Here is the code for navigationService that's being referenced:

import { Injectable } from '@angular/core';

@Injectable()
export class NavigationService {
onEditMode:boolean;
auth2:any;
constructor() {
    this.onEditMode=true;
}

getEditMode(){
    return this.onEditMode;
}

setEditMode(editMode:boolean){
    this.onEditMode=editMode;
}

setAuth2(auth2:any){       
    this.auth2=auth2;

}

getAuth2(){
    return this.auth2;

}

}

Additionally, here is the login.component.ts snippet where the auth2 object is set and used from navigationService.ts:

onGoogleLoginSuccess = (loggedInUser) => {
    
    // Code for setting auth2 object
}

The onGoogleLoginSuccess function is called within login.component.html like so:

<div style="margin-left:8% !important" id="{{googleLoginButtonId}}"></div>

Since upgrading my router to the latest Angular2 Release Candidate version, I have encountered the following error when attempting to sign out:

Error in component.html/navbar.component.html:12:33
ORIGINAL EXCEPTION: TypeError: Cannot read property 'signOut' of undefined

If further information or components are needed, please feel free to inquire. Given that everything was functioning properly before the update, any insights into resolving this issue are greatly appreciated.

Answer №1

Revision

Awaiting further details...


The code snippet below indicates that auth2:any; is being referenced as undeclared. Has setAuth2 been invoked prior to signOut()?

import { Injectable } from '@angular/core';

@Injectable()
export class NavigationService {

    onEditMode:boolean;
    auth2:any;
    constructor() {
        this.onEditMode=true;
    }

    getEditMode(){
        return this.onEditMode;
    }

    setEditMode(editMode:boolean){
        this.onEditMode=editMode;
    }

    setAuth2(auth2:any){       
        this.auth2=auth2;

    }

    getAuth2(){
        return this.auth2;

    }

}

Based on the limited information and provided code, it appears there may be a logical inconsistency in the logout process.

Within the signOut() function, window.location.reload() refreshes the page at its current URL, effectively clearing all variables/objects. Subsequently, upon reload, the application attempts to sign out again (potentially due to the URL).

In your navbar.component, consider implementing additional logic within ngInit() to address this scenario.

Alternatively, can your code function without utilizing window.location.reload()? Its use with Angular 2, particularly in conjunction with routing, seems unconventional.

Answer №2

After some trial and error, I discovered that signing out using localhost was causing an issue. To address this, I implemented a workaround by including a specific code block when deploying the website, and keeping it commented out while running the website on localhost.

Below is the signOut() function that I added to my navbar.component.ts file:

signOut() {

    //////////////////////////////////////// Uncomment block for live deployment //////////////////////////////


    // var auth2 = gapi.auth2.getAuthInstance();
    // auth2.signOut().then(function () {
    //     console.log('User signed out.');
    // });


    //////////////////////////////////////////////////////////////////////////////////////////////////////////

    sessionStorage.clear();
    localStorage.clear();
    this.router.navigate(['/']);
    window.location.reload();

}

It's worth noting that there were errors with getAuthInstance when testing it in localhost, but after deploying the web application to a server, everything worked smoothly.

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

Understand and extract data from a JSON array using Typescript

Here is a JSON response I received from a remote server: { "string": [ { "id": 223, "name": "String", "sug": "string", "description": "string", "jId": 530, "pcs": [{ "id": 24723, "name": "String", ...

When using `ng lint --fix=true`, the linting errors remain unresolved and are not fixed

Upon initializing a fresh project using "ng new" and adjusting tslint.json to utilize tabs instead of spaces, I encountered an issue where running "ng lint --fix=true" did not result in any changes to the .ts files: https://i.sstatic.net/yPJu2.png ng lint ...

"Encountering a 404 Error when attempting to refresh an Angular 13 application hosted on an Apache

I have developed a prototype web application and now need to deploy it on an Apache server running Ubuntu OS. After building the web app, I hosted it on my local machine for testing purposes. I have configured the .htaccess file as follows: RewriteEngine ...

Is there a way for me to confirm the presence of a particular object within an array and return a true value

I am working on a form in Angular that includes checkboxes. I want to automatically check the checkbox if the user has a specific role. Here is my current approach: <form [formGroup]="rolesForm"> <label formArrayName="roles" *ngFor=" ...

connecting and linking template content with an Observable

I have a CRUD page that needs to be updated after every operation. I have implemented Observable and the CRUD functions (specifically Add and Delete) are working fine, but I need to manually refresh the page to see the changes reflected. After trying to ...

Angular Unit Test - Overcoming CORS Issue During XMLHttpRequest Access

I am currently facing a CORS problem within my Angular test spec file. I am unsure of how to resolve this issue, which occurs in the second line. beforeEach(() => { fixture = TestBed.createComponent(FhcComponent); //THIS IS WHERE THE ISSUE ARISES ...

Combine the power of Google authentication with Python and the Dash framework

I am keen on integrating Google authentication into a Dash app. I recently came across a valuable post on how to work with Flask here which helped me set up the Google API access and display the authentication screen for users to log in with their Google a ...

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

Learning to extract information from elements within components in a flexbox using Angular

Is there a way to access the element width of child components within a parent component that utilizes flex box? I am hoping to determine if the list is overflowed so I can adjust the visibility of elements accordingly. If an overflow occurs, I would like ...

Angular 2: A guide to connecting Input with model property using getter and setter functions

I'm currently developing an Angular 2 web application. The model I have created consists of a few primary properties, along with other properties that are calculated based on those primary values. For each property in my model, I have implemented get ...

Converting a string into a Date in Typescript while disregarding the timezone

Upon receiving a date in string format like this (e.g.): "11/10/2015 10:00:00" It's important to note that this is in UTC time. However, when creating a Date object from this string, it defaults to local time: let time = "11/10/2015 10:00:00"; let ...

Is it feasible to utilize AngularFire and Firebase in tandem?

Currently, I am working with Ionic2 and firebase. There are two methods to initialize firebase in app.ts that I have come across. I am wondering which one is the recommended approach and how can both functions be utilized together? When I initialized fireb ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Tips for aligning flex items based on the previous item in a flex container

Place 'text1' beneath the number 1 (so that the 't' character is under the 1), and 'text2' beneath the number 5 (with the '2' character under the number 5) This should be done dynamically to adjust to a varying numb ...

Angular 4/5 | Custom Dropdown Component

I have been working on a custom dropdown directive in Angular that I can attach to any DOM element. Below is the code for my directive: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appDropdown]' ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Jest snapshot tests are not passing due to consistent output caused by ANSI escape codes

After creating custom jest matchers, I decided to test them using snapshot testing. Surprisingly, the tests passed on my local Windows environment but failed in the CI on Linux. Strangely enough, the output for the failing tests was identical. Determined ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...