无法解决的CLI错误是什么意思,您如何修复它? [英] What does " Can't resolve 'auth0-js' " CLI error mean, and how do you fix it?

查看:18
本文介绍了无法解决的CLI错误是什么意思,您如何修复它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用auth0进行角度身份验证。我已经安装了认证0、认证0-js和认证0-反应,但我的应用程序仍然无法加载。CLI一直显示以下错误:

./src/app/Services/auth.service.ts:2:0-34-错误:找不到模块:错误:无法在‘C:UsersOwnerDesktopcoding_course_docsAngularAudioPlayersrcappservices’

中解析‘auth0-js’

我想知道是必要的程序包安装不正确还是有什么问题。

这是我的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)}`);

    }

  };

}


如有任何有关如何使应用程序正常工作的帮助,我们将不胜感激!

推荐答案

我认为您使用的包不正确。尝试执行npm install @auth0/auth0-angular 而您正在寻找的是auth0角,请找到它here

这篇关于无法解决的CLI错误是什么意思,您如何修复它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆