1
votes

core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'email' of undefined TypeError: Cannot read property 'email' of undefined at AuthService.push../src/app/services/auth.service.ts.AuthService.getSearchs

This is the error which I get when I try to do the next function.

  public getSearchs():Observable<any>{
    let url: string = AppSettings.API_ENDPOINT+'searches?email='+this.userProfile.email;
    console.log(url);
    return this.http.get(url);
  }

Sometimes works well.

  auth0 = new auth0.WebAuth({
    clientID: ''xxxxx",
    domain: 'xxxxx.eu.auth0.com',
    responseType: 'token id_token',
    audience: 'https://xxxxeu.auth0.com/api/v2/',
    redirectUri: 'http://localhost:4200/',
    scope: 'openid email profile'
  });

UPDATE:

// src/app/auth/auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import * as auth0 from 'auth0-js';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { AppSettings } from './appSetings';
import { map, filter, switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { EmailValidator } from '@angular/forms';

@Injectable()
export class AuthService {

  private _idToken: string;
  private _accessToken: string;
  private _expiresAt: number;
  public userProfile: any;



  auth0 = new auth0.WebAuth({
    clientID: 'xW',xx
    domain: 'x.eu.autxxh0.com',
    responseType: 'token id_token',
    audience: 'https://XXXX.eu.auth0.com/api/v2/',
    redirectUri: 'http://localhost:4200/',
    scope: 'openid email profile'
  });

  constructor(public router: Router, public http:HttpClient) {
    this._idToken = '';
    this._accessToken = '';
    this._expiresAt = 0;
  }

  public get accessToken(): string {
    return this._accessToken;
  }

  public get idToken(): string {
    return this._idToken;
  }

  public login(): void {
    this.auth0.authorize();
  }


  public handleAuthentication(): void {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        window.location.hash = '';
        this.localLogin(authResult);
        this.router.navigate(['/home']);
      } else if (err) {
        this.router.navigate(['/home']);
        console.log(err);
      }
    });
  }

  private localLogin(authResult): void {
    // Set the time that the Access Token will expire at
    const expiresAt = (authResult.expiresIn * 1000) + Date.now();
    this._accessToken = authResult.accessToken;
    this._idToken = authResult.idToken;
    this._expiresAt = expiresAt;
  }


  public renewTokens(): void {
    this.auth0.checkSession({}, (err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.localLogin(authResult);
      } else if (err) {
        alert(`Could not get a new token (${err.error}: ${err.error_description}).`);
        this.logout();
      }
    });
  }

  public logout(): void {
    // Remove tokens and expiry time
    this._accessToken = '';
    this._idToken = '';
    this._expiresAt = 0;

    this.auth0.logout({
      returnTo: window.location.origin
    });
  }

  public isAuthenticated(): boolean {
    // Check whether the current time is past the
    // access token's expiry time
    return this._accessToken && Date.now() < this._expiresAt;
  }


  public getProfile(cb): void {
    if (!this._accessToken) {
      throw new Error('Access Token must exist to fetch profile');
    }

    const self = this;
    this.auth0.client.userInfo(this._accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  //Get all searchs saved by user logged
  public getSearchs():Observable<any>{
    let email = this.userProfile.email;
    let url: string = AppSettings.API_ENDPOINT+'searches?email='+email;
    console.log(url);
    return this.http.get(url);
  }

}

UPDATE 2:

I added this code but it doesnt work yet.

     ngOnInit() {
        if(this.auth.userProfile)
        {
          this.profile = this.auth.userProfile;
        }else{
          console.log("error");
          this.auth.getProfile((err, profile) =>{
            this.profile = profile;
          });
        }






  **Solution**




 ngOnInit() {
    if(this.auth.userProfile)
    {
      this.profile = this.auth.userProfile;
    }else{
      console.log("error");
      this.auth.getProfile((err, profile) =>{

      this.auth.getSearchs(profile).subscribe(data=>{
        this.searches = data;
      },
      (err) => {
        console.log("Ha surgido un error")
      }); 

      });
    }

  }
1
it looks like your userProfile object is not always created before you call getSearchs method. If you share more code about how your userProfile is created then it will be more helpful - Piyush
@Piyush I´ve shared all the code. - csvg2
@csvg2 when is getProfile() is getting called and when getSearchs() is getting called in the component? - Koushik Ravulapelli
when the profile is not returned, in that case it will not assign any value to userProfile. In that case u will see that error. One solution is to check for userProfile existence then assign email. let email = ""; if (this.userProfile) { email = this.userProfile.email; } - Piyush
@CodingFreak I dont call getProfile, should i call it? I call getSearchs in ngOnInit of the component but when I enter in that componer i am alredy in session. - csvg2

1 Answers

0
votes

You can try passing the profile variable directly to that function in your component. You will need to replace this.auth.userProfile with a profile param.

In auth.service.ts

public getSearchs(profile):Observable<any>{
    let email = profile.email;
    let url: string = AppSettings.API_ENDPOINT+'searches?email='+email;
    console.log(url);
    return this.http.get(url);
}

In profile.component.ts

this.auth.getSearches(this.profile);