Error message "Unable to access property 'picture' of null" occurs in Angular 2 with Auth0 upon successful login

I've successfully implemented Auth0 authentication in my Angular 2 application. However, upon signing in, I encounter an error stating "Cannot read property 'picture' of null." Oddly enough, if I refresh the page, the user is shown as logged in and the image appears without any errors in the console.

Here's the error message I receive: https://i.sstatic.net/dXTwc.png

For those interested, here's the link to the GitHub repository: https://github.com/cstodor/Auth0Lock-Angular2


Below is the code snippet for the affected element in header.component.html:

<span *ngIf="auth.authenticated()">
    <img class="img-circle" width="25" height="25" src="{{ profile.picture }}"> {{ profile.nickname }}
</span>


header.component.ts:

profile: any;

constructor(private auth: Auth) {
    this.profile = JSON.parse(localStorage.getItem('profile'));
}


auth.service.ts

import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig } from './auth.config';

let Auth0Lock = require('auth0-lock').default;

@Injectable()
export class Auth {
    // Configure Auth0
    lock = new Auth0Lock(myConfig.clientID, myConfig.domain, {});
    profile: any;

    constructor(private router: Router) {
        this.lock.on("authenticated", (authResult: any) => {
            this.lock.getProfile(authResult.idToken, function (error: any, profile: any) {
                if (error) {
                    throw new Error(error);
                }
                localStorage.setItem('id_token', authResult.idToken);
                localStorage.setItem('profile', JSON.stringify(profile));
                console.log('PROFILE: ' + profile);
            });
        });
    }

    public login() {
        // Display the widget
        this.lock.show();
    };
    
    public authenticated() {
        // Check for unexpired JWT
        return tokenNotExpired();
    };

    public logout() {
        // Remove tokens from localStorage
        localStorage.removeItem('id_token');
        localStorage.removeItem('profile');
    };
}

Any advice on how to resolve this issue? Your input would be greatly appreciated!

Answer №1

profile is not available when the ngIf processes, leading to an exception being thrown. To resolve this issue, update your ngIf statement to

*ngIf="auth.authenticated() && profile"
so that the processing is delayed until profile exists.

It seems like you may be waiting for a promise to resolve, or you might have forgotten to set profile after authenticating, which could explain why profile is null.

Answer №2

After some help from a friend, we were finally able to resolve the issue we were facing. It turned out that the profile was trying to retrieve data from localStorage when HeaderComponent was created, but the value in localStorage is only available once a user has successfully logged in.

In order to address this issue, it was necessary to subscribe to auth for profile updates and fetch the updated profile from there.

If you're interested, you can check out the updated code on our GitHub repository:
https://github.com/cstodor/Auth0Lock-Angular2

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

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

Indicate when a ReplaySubject has reached its "completion" signal

I'm currently looking for an effective way to indicate when a ReplaySubject is empty. import {ReplaySubject} from 'rxjs/ReplaySubject'; const rs = new ReplaySubject<Object>(); // ... constructor(){ this.sub = rs.subscribe(...); } ...

Create a new Angular service without dependency injection

There's an Angular service that listens to an event on the $rootScope within its constructor method. This particular service is never actually injected anywhere in the application, which means it is not properly initialized. To work around this issue ...

Transforming strings of HTML into objects in the DocX format

After developing a TypeScript script that transforms a JSON string into a Word Doc poster using Docx, I encountered a hurdle. Certain sections of the JSON may contain HTML tags, such as <br/>, <i>, <p>, and I need a way to pass the stri ...

Errors related to reducer types in createSlice of Redux Toolkit

As I embark on a new React-Redux project with Typescript, I find myself facing some challenges despite my previous experience. While my knowledge of React and Redux is solid, I am still getting acquainted with Redux toolkit. Transitioning from a typed back ...

Creating descriptions for types in Vue.js using TypeScript

When running this code snippet, you might encounter the error message 'description' does not exist in PropValidator export default Vue.extend( { name: 'something', props: { 'backgro ...

Could components be responsible for data initialization delays?

I am encountering an issue with initializing "elements" in COMPONENTS using data received from a web request. For example (in pseudo code): <elem elemOpts="$ctrl.elemOpts" /> ....... ctrl = this; ctrl.web_data = []; ctrl.elemOpts = { data : c ...

What is the best way to integrate a service-defined class into a component in Angular?

Is there a way to utilize a class that is defined in a service within a component? The Service.ts file includes a class that I would like to use in my component. Despite injecting the service into the component, I am encountering difficulties in accessing ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

Unable to clear form using `$setPristine` command

Whenever I try to execute the code below to reset my form, I encounter an error: $scope.resetForm = function () { $scope.testForm.$setPristine(); } Here is the HTML snippet: <form name="testForm" > <label class="it ...

Issue with AngularJS: error:areq Invalid Argument

<!DOCTYPE html> <html ng-app> <body data-ng-controller="SimpleController"> <div class="container"> Title: <br/> <input type="text" ng-model="title" />{{title}} <br/> ...

Scope of Ionic2 Storage Promise.all function

Looking for help with assigning an Ionic2 Storage value to a local variable. When I console.log inside the .then, it works fine, but the value seems to be limited to that function/method only. Most examples I've found demonstrate how to 'get&apos ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

https://i.sstatic.net/7CzRg.png Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically intere ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

The reason why Class-validator doesn't handle fields that lack a decorator in Nest js

After creating a DTO for my endpoint, I encountered an issue where the class-validator stops checking a field if it doesn't have a decorator assigned to it. Even though I need the field to be mandatory and checked, it gets skipped. DTO: import {IsNum ...

What is the procedure for extracting specific elements from a JSON response and transforming them into an array that adheres to a defined

In order to retrieve the JSON response of a GET request made by a service within my app to our backend, extract specific parts from it, and store them in an Array based on an Interface I have created for future use. Here is a sample of the JSON data: [{ ...

Typescript's array of functions

In my code, I currently have an engage(ability: number, opponent: Creature) function that is responsible for executing one of three different attacks based on the ability chosen. strike(opponent: Creature){} claw(opponent: Creature){} fireball(opponent: C ...

Creating objects based on interfaces in TypeScript is a common practice. This process involves defining

Within my TypeScript code, I have the following interface: export interface Defined { 4475355962119: number[]; 4475355962674: number[]; } I am trying to create objects based on this interface Defined: let defined = new Defined(); defined['447 ...

Implementing a jQuery date selection feature with Rails 3.2.8 and AngularJS: troubleshooting date display and persistence issue

Struggling to get the rails+angularjs+jQuery datepicker trio to work in harmony. The issue arises when trying to display dates retrieved from the backend. When data is requested from the backend, it is received in JSON format like this: {"id":1,"ragione_ ...

Invoke the LazyQuery Hook within a Function

My GraphQL query implementation is as follows: const [loadUsers, { loading, data }] = useLazyQuery(LoadUsersQuery); When I utilize this code snippet in my project, the lazy query loadUsers functions properly and displays the results: return ( <d ...