无法读取媒体资源“电子邮件” Auth0

时间:2019-05-20 18:36:36

标签: angular auth0

core.js:15724错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性“电子邮件” TypeError:无法读取未定义的属性“电子邮件”     在AuthService.push ../ src / app / services / auth.service.ts.AuthService.getSearchs

这是我尝试执行下一个功能时遇到的错误。

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

有时候效果很好。

  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'
  });

更新:

// 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);
  }

}

更新2:

我添加了此代码,但尚无法正常工作。

     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 个答案:

答案 0 :(得分:0)

您可以尝试将配置文件变量直接传递到组件中的该函数。您将需要使用配置文件参数替换this.auth.userProfile。

在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);
}

在profile.component.ts

this.auth.getSearches(this.profile);