The existing object contains a value, however, attempting to access its property results in an undefined value being

I have discovered some unusual occurrences in my coding. Specifically, I have an AuthService that handles authentication requirements for my applications, including the authentication token.

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl:ModalController,public auth: AuthService) {

  }

  ionViewDidLoad() {
    console.log(this.auth)
    console.log(this.auth.loggedIn)
    if(this.auth.loggedIn){
      console.log(this.auth);
      this.navCtrl.push("TabsPage");
    }    
  }
}

When I execute

console.log(this.auth)

it returns authentication. However, when I run

console.log(this.auth.loggedIn)

it returns null. This is perplexing to me.

This is my auth.service.ts:

import { Injectable, NgZone, Component } from '@angular/core';
import { Storage } from '@ionic/storage';

// Import AUTH_CONFIG, Auth0Cordova, and auth0.js
import { AUTH_CONFIG } from './auth.config';
import Auth0Cordova from '@auth0/cordova';
import * as auth0 from 'auth0-js';

@Injectable()
export class AuthService {
  Auth0 = new auth0.WebAuth(AUTH_CONFIG);
  Client = new Auth0Cordova(AUTH_CONFIG);
  accessToken: string;
  user: any;
  loggedIn: boolean;
  loading = true;

  constructor(
    public zone: NgZone,
    private storage: Storage
  ) {
    this.storage.get('profile').then(user => this.user = user);
    this.storage.get('access_token').then(token => this.accessToken = token);
    this.storage.get('expires_at').then(exp => {
      this.loggedIn = Date.now() < JSON.parse(exp);
      this.loading = false;
    });

  }

  login() {
    this.loading = true;
    const options = {
      scope: 'openid profile offline_access'
    };
    // Authorize login request with Auth0: open login page and get auth results
    this.Client.authorize(options, (err, authResult) => {
      if (err) {
        throw err;
      }
      // Set access token
      this.storage.set('access_token', authResult.accessToken);
      this.accessToken = authResult.accessToken;
      // Set access token expiration
      const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
      this.storage.set('expires_at', expiresAt);
      // Set logged in
      this.loading = false;
      this.loggedIn = true;
      // Fetch user's profile info
      this.Auth0.client.userInfo(this.accessToken, (err, profile) => {
        if (err) {
          throw err;
        }
        this.storage.set('profile', profile).then(val =>
          this.zone.run(() => this.user = profile)
        );
      });
    });
  }

  logout() {
    this.storage.remove('profile');
    this.storage.remove('access_token');
    this.storage.remove('expires_at');
    this.accessToken = null;
    this.user = null;
    this.loggedIn = false;
  }

  isLoggedIn() :boolean{
    return this.loggedIn;
  }
}

As I use Ionic3 and Auth0 authentication, I initially suspected that the issue was due to not using a public identifier on my property. Even after making changes by adding a public keyword or creating a getter method, the problem persists.

Answer №1

When the chrome console evaluates an object, it may show a tiny blue info icon when you open it in the console. The message displayed will say:

Value was evaluated just now

This could be due to changes in the object content between the time it was logged and when it was opened in the console.

The asynchronous nature of the login action causes the `loggedIn` property on the auth object to be set after the `ionViewDidLoad` is called. One possible solution could be to set the auth inside an APP_INITIALIZER provider, or implement an Observable on your auth to listen for authentication changes.

Answer №2

1. Make sure to check if this.loggedIn is defined before assigning a value to it. Try using console.log(this.auth.loggedIn) after logging in to verify the status.

2. If you are facing issues with the loggedIn variable being undefined, assign a default value of false like so: loggedIn: boolean; => loggedIn: boolean=false;. This should help resolve the problem.

Also, make sure to include the following code snippet in another component:

 ngOnInit() {
    console.log(this.auth.loggedIn)
  }

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

Issues with jQuery functionality occurring when trying to display or hide div contents on dynamically loaded AJAX content

I have encountered an issue while working on a project that involves showing or hiding a div based on the selection of a drop down value. The show/hide functionality works perfectly when implemented on the same page, but it fails when I try to do the same ...

Oops! Looks like the connection has been abruptly cut off from the ASYNC node

Is there a way to properly close an async connection once all data has been successfully entered? Despite attempting to end the connection outside of the loop, it seems that the structure is being finalized after the first INSERT operation CODE require( ...

What is the best way to retrieve seat number upon clicking in React Native?

I have implemented a for loop and assigned its value in the click function to retrieve the seat number when a seat is clicked. However, I am only getting the last number of the for loop every time a seat is clicked. Can someone guide me on how to obtain th ...

The issue with Express connect-flash only showing after a page refresh instead of instantly displaying on the same page needs to be addressed

Here is the registration route code snippet: router.post("/register", function(req, res){ var newUser = new User({username: req.body.username}); User.register(newUser, req.body.password, function(error, user){ if(error){ req.fl ...

Which release of "ngx-bootstrap" is compatible with "Angular 17"?

Here's the scoop I attempted to download ngx-bootstarp but couldn't find a suitable version. I searched online, but there was no information available. Checking the list on the Angular Bootstrap official website, I noticed that version 17.0.0 ha ...

Is there a way to retrieve the DOM element from an ngFor array?

Is there a way to access the actual element of an ngFor loop in order to manipulate it within the Component.ts file? Here's an example scenario: //.html <div *ngFor="let element of elements"> <md-card>{{element}} <but ...

Sending an AJAX request from one subdomain to another subdomain within the same domain

Is it true that cross-domain ajax requests require a 'proxy' server to be used? But what if an ajax request is made from server1.example.com to server2.example within the same domain of example.com? Would that still not work? I've noticed ...

How much time can pass between two clicks in order to activate a double-click event?

How long is the maximum delay between two clicks that will still activate a double-click event? Does this delay vary between plain JavaScript, jQuery, and AngularJS? Additionally, in jQuery, what time intervals do the fast and slow keywords represent? For ...

Tips for capturing an express proxy error in React?

I set up an express server as a proxy for my React app, but I am facing an issue where I cannot get the error response back in my React code. No matter if I use `return next(err)` or `res.send(err)`, the latter gets stuck in the `then` block and does not t ...

Having trouble deploying Firebase Cloud function following the migration to Typescript

After following the steps outlined in the firebase documentation to convert my cloud functions project to TypeScript (see https://firebase.google.com/docs/functions/typescript), I encountered an error when attempting to deploy using 'firebase deploy - ...

Is there a way to retrieve the watch time of an HTML5 video using PHP without relying on external software?

<video id='myVideo' controls autoplay> <source src='a.mp4#t=00:00:00' type=video/mp4> </video> Is there a way to calculate the watch time of an HTML5 video using PHP and save it to a variable without the need for ...

Can you outline the key distinctions between AngularJS and ReactJS?

Looking to create a website that will be converted into a mobile application, I realize that my expertise lies more in desktop and Android native development rather than web client side development. After some research, I have decided to utilize HTML5, CSS ...

Retrieve JSON-formatted HTML content to display as HTML within a React component

Wondering how to make the link actually render as a clickable hyperlink. Currently, when I read this line of text from my Json file, React displays the link as plain text rather than a clickable link. someData.json [{ "about": "John has a blog you ...

Angular dynamically selects a dropdown option when the page is loaded

Check out this dropdown example: <div class="col-md-6"> <div class="form-group> <label class="control-label">Role</label> < ...

Obtain the result of the Mongoose find operation

Greetings, I am facing a challenge with accessing elements returned from a find operation in Mongoose due to the asynchronous nature and callback functions. Below is the code for reference: function retrieveBudgets(email, callback) { models.User.f ...

Update the content of a div using jQuery and AJAX by targeting a specific button ID

I am in the process of developing a website that functions as an interactive "choose your own adventure" game. The page will present users with a question along with three different choices represented as buttons. Upon selecting one of the options, jQuery ...

Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService. The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status. On the ot ...

How to Transfer Data from SuperAgent Library Outside the .then() Block?

I have a dilemma in my Nodejs project with two interdependent files. The key to this issue lies in the usage of a crucial library known as SuperAgent (I need it) Check out SuperAgent Library Here In file1.js const file2 = require('./file2'); ...

Angular 4 encounters performance issues when rendering numerous base64 images simultaneously

I'm currently working on a private project that involves using Angular 4 (specifically version 4.1.2). One issue we're facing is related to rendering multiple base64 images on an HTML page. The performance of the application significantly drops w ...

Keeping the Angular Material sidenav constantly expanded on desktop screens

I just started learning Angular and I'm attempting to implement the sidenar component from Angular Material (current version). Here is the code snippet inside the main-nav component: <mat-sidenav-container class="sidenav-container" autosize> ...