【问题标题】:Cannot read property ‘email’ Auth0无法读取属性“电子邮件”Auth0
【发布时间】:2019-05-21 17:02:39
【问题描述】:

core.js:15724 ERROR 错误:未捕获(承诺中):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")
      }); 

      });
    }

  }

【问题讨论】:

  • 看起来您的 userProfile 对象并不总是在您调用 getSearchs 方法之前创建。如果您分享更多有关如何创建 userProfile 的代码,那么它将更有帮助
  • @Piyush 我已经分享了所有代码。
  • @csvg2 何时在组件中调用getProfile() 以及何时调用getSearchs()
  • 当配置文件没有返回时,在这种情况下它不会为 userProfile 分配任何值。在这种情况下,您将看到该错误。一种解决方案是检查 userProfile 是否存在,然后分配电子邮件。让电子邮件=“”; if (this.userProfile) { 电子邮件 = this.userProfile.email; }
  • @CodingFreak 我不调用 getProfile,我应该调用它吗?我在组件的 ngOnInit 中调用 getSearchs,但是当我进入该组件时,我已经在会话中。

标签: angular auth0


【解决方案1】:

您可以尝试将配置文件变量直接传递给组件中的该函数。您需要将 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);

【讨论】:

  • 这与我所做的类似,现在我直接调用 getProfile 中的函数 getSearchs ,看起来效果很好。谢谢
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
相关资源
最近更新 更多