【问题标题】:What does " Can't resolve 'auth0-js' " CLI error mean, and how do you fix it?“Can't resolve 'auth0-js'” CLI 错误是什么意思,如何解决?
【发布时间】:2021-12-04 15:09:59
【问题描述】:

我正在使用 auth0 在 Angular 中进行身份验证。我已经安装了 auth0、auth0-js 和 auth0-react,但我的应用程序仍然无法加载。 CLI 不断给我这个错误:

./src/app/services/auth.service.ts:2:0-34 - 错误:找不到模块:错误:无法解析“C:\Users\Owner\Desktop”中的“auth0-js” \coding_course_docs\AngularAudioPlayer\src\app\services'

我想知道是否必要的软件包安装不正确或什么的。

这是我的 pacakge.json:

{
  "name": "angular-audio-player",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.9",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/material": "^12.2.9",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "@auth0/auth0-angular": "^1.7.0",
    "@auth0/auth0-react": "^1.8.0",
    "@types/auth0-js": "^9.14.5",
    "moment": "^2.29.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.4",
    "@angular/cli": "~12.2.4",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^12.11.1",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "node-scss": "^7.0.3",
    "ts-jest": "^27.0.7",
    "typescript": "~4.3.5"
  }
}

这是 tsconfig:

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

这是 tsconfig.app:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"

  ],
  "exclude": [
    "**/*.spec.ts"
  ]
}

这里还有 auth.service 文件:

import { Injectable } from '@angular/core';

//npm install --save @types/auth0-js (CLI cmd)
import * as auth0 from 'auth0-js';

import { environment } from '../../environments/environment';

import{

  Observable,
  BehaviorSubject,
  bindNodeCallback, 
  of
} from 'rxjs';

import { Router } from '@angular/router';


@Injectable({
  providedIn: 'root'
})
export class AuthService {

  //instance of auth0-WebAuth that is used for authentication
  auth0 = new auth0.WebAuth({

    clientID: environment.auth0.clientID,

    domain: environment.auth0.domain,

    responseType: 'token id_token',

    scope: 'openid profile email'

  });

  //'localStorage' keys (for storing authentication and user profile data) that track whether or not to renew token
  private _authFlag = 'isLoggedIn';
  
  private _userProfileFlag = 'userProfile';


  //'Observable' that stores authentication data & emits access token
  token$!: Observable<string>;

  //'BehaviorSubject' that creates stream for user profile data
  userProfile$ = new BehaviorSubject<any>(null);


  //Authentication Navigation
  onAuthSuccessUrl = '/';

  onAuthFailureUrl = '/';

  logoutUrl = environment.auth0.logoutUrl;

  /*parseHash$ = 
  After authentication occurs, you can use the parseHash method to parse a URL hash fragment 
  when the user is redirected back to your application in order to extract 
  the result of an Auth0 authentication response*/

  //Create observable of Auth0, then parseHash() function to gather 'auth' results
  parseHash$ = bindNodeCallback(this.auth0.parseHash.bind(this.auth0));

  //Create observable of Auth0 checkSession() function to verify authorization server session and renew tokens
  checkSession$ = bindNodeCallback(this.auth0.checkSession.bind(this.auth0));
  


  constructor(private router: Router) { 

    //'get' user info from 'localStorage'
    const userProfile = localStorage.getItem(this._userProfileFlag);

    //checks if there is any user info stored
    if (userProfile) {

      //if there IS user info stored, emit it via the 'userProfile$' BehaviorSubject
      this.userProfile$.next(JSON.parse(userProfile));

    }
  }

  //authorize user
  login = () => this.auth0.authorize();
  

  /*
  uses the parseHash$ 'Observable' to parse the auth result, 
  then sets authentication state using 'this._setAuth()', takes 'authResult' from parsed Auth data, and initializes 'token$', 
  then redirects to 'onAuthSuccessUrl' 
  */
  handleLoginCallback = () => {

    if (window.location.hash && !this.authenticated) {

      //parse authResult from Observable
      this.parseHash$().subscribe({

        next: authResult => {
          //takes authResult from parsed Auth data sets authentication state
          this._setAuth(authResult);

          window.location.hash = '';

          //redirect to 'onAuthSuccessUrl'
          this.router.navigate([this.onAuthSuccessUrl]);

        },

        error: err => this._handleError(err)

      });

    }

  };

  //Save authentication data and update login status subject
  private _setAuth = (authResult: any) => {

    //take authResult from parsed Auth data and initialize 'token$' Observable
    this.token$ = of(authResult.accessToken);


    const userProfile = authResult.idTokenPayload;

    //Emit value for user data subject
    this.userProfile$.next(userProfile);

    //save 'userProfile' in 'localStorage'
    localStorage.setItem(this._userProfileFlag, JSON.stringify(userProfile));

    //Set flag in local storage stating that this app is logged in
    localStorage.setItem(this._authFlag, JSON.stringify(true));



    const renewAuth = () => {

      //checks if user is authenticated or not
      if (this.authenticated) {

        //checkSession to see if 'authResult' is valid
        this.checkSession$({}).subscribe({

          next: authResult => this._setAuth(authResult),

          error: err => {

            localStorage.removeItem(this._authFlag);

            localStorage.removeItem(this._userProfileFlag);

            this.router.navigate([this.onAuthFailureUrl]);

          }

        });

      }

    }

    const logout = () => {

      //Set authentication status flag in local storage to false
      localStorage.setItem(this._authFlag, JSON.stringify(false));

      //remove the userProfile data
      localStorage.removeItem(this._userProfileFlag);

      //refresh, then redirect to homepage
      this.auth0.logout({

        returnTo: this.logoutUrl,

        clientID: environment.auth0.clientID

      });
      
    };

  }

  //checks if user is authenticated or not using 'localStorage' flag
  get authenticated(): boolean {

    return JSON.parse(localStorage.getItem(this._authFlag) || '{}');

  }

  
  //Utility functions
  private _handleError = (err: { error_description: any; }) => {

    if (err.error_description) {

      console.error(`Error: ${err.error_description}`);

    } else {

      console.error(`Error: ${JSON.stringify(err)}`);

    }

  };

}


感谢任何有关如何使应用程序正常工作的帮助!

【问题讨论】:

  • 您好,您可以将 auth.service.ts 附加到问题中吗?谢谢。
  • 它现在就在那里。

标签: angular command-line-interface npm-install auth0


【解决方案1】:

我认为您使用了错误的软件包。尝试做npm install @auth0/auth0-angular 你要找的是auth0-angular,找到它here。

【讨论】:

  • 这似乎有效。唯一的问题是 WebAuth() 似乎没有位于 auth0-angular 的导入库中,这导致另一个错误。
猜你喜欢
  • 2020-04-22
  • 2021-06-25
  • 2013-12-08
  • 2014-05-02
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多