Auth0服务无法使用Angular 2找到容器

Auth0 service unable to find container using Angular 2

本文关键字:Angular 服务 Auth0      更新时间:2023-09-26

我正在创建一个Angular 2 SPA用于学习目的,并集成Auth0来处理身份验证。我有一个auth.service.ts,它将在我的应用程序中的不同位置被调用,例如在顶部导航栏中用于注销,在auth页面上用于处理登录和注册。

当试图通过设置容器选项将Auth0容器放置在div中时,我得到以下错误:找不到id为auth-container的元素

我怎么能让权威。服务知道如何/在哪里查找auth-containerdiv?将所有的逻辑都放在auth.component.ts中可能是不可取的,因为auth.component。Service将被用于其他地方的其他功能,这些地方也使用了lock变量。

auth.service.ts

import { Injectable }      from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig }        from './auth.config';
declare var Auth0Lock: any;
var options = { container: 'auth-container' };
@Injectable()
export class Auth {
    lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options);
    constructor() {
        this.lock.on('authenticated', (authResult) => {
            localStorage.setItem('id_token', authResult.idToken);
        });
    }
    public authenticated() {
        return tokenNotExpired();
    };
    public logout() {
        localStorage.removeItem('id_token');
    };
}

auth.component.ts

constructor(public auth: Auth) {
    auth.lock.show();
}

auth.component.html

 <div id="auth-container"></div>

他们没有让你的生活变得轻松,但我错误地让它工作。

试试这个:

auth.component.ts

ngOnInit() {
    this.auth.login()
  }

从构造函数中删除

auth.lock.show();

Service不是一个容器,它是一个服务,当登录函数被调用时,它会提供一个弹出窗口。

所以,要在任何你喜欢的地方重用它,你需要将认证服务注入到你想从中调用认证服务的组件中。然后,你只需调用这个方法。例如,下面是我的Start组件的html。您可以看到,登录按钮的click事件被绑定到组件(Start组件)的"submitLogin()"方法:

<div class="splash-back" *ngIf="!authService.authenticated()">
  <div id="splash">
    <div id="logo"><span class="silver">GCO</span>TeamKeeper
      <p class="silver tagline">The other teams could make trouble for us if they win.</p>
      <p class="silver attribution">~ Yogi Berra</p></div>
    <div class="call">
      <br>
      <button class="btn-sign-in" (click) = "submitLogin()">Sign up or Log in</button>
    </div>
    <!--<mtm-authentication></mtm-authentication>-->
  </div>
</div>
下面是开始组件代码(注意在构造函数中注入了身份验证服务):
@Component({
  selector: 'tk-start',
  templateUrl: './start.component.html',
  styleUrls: ['./start.component.css']
})
export class StartComponent implements OnInit {
  constructor(private authService: UserAuthenticationService) { }
  ngOnInit() {
  }
  submitLogin(){
    this.authService.login();
  }
}
为了使这个例子完整,下面是我的认证服务代码:
import {Injectable} from "@angular/core";
import { tkConfig } from './user-authentication.config';
import {Router} from "@angular/router";
import {tokenNotExpired} from "angular2-jwt";

let Auth0Lock = require('auth0-lock').default;
@Injectable()
export class UserAuthenticationService {
  // Configure Auth0
  userProfile: Object;
  lock = new Auth0Lock (tkConfig.clientID, tkConfig.domain, {
      avatar: null,
      theme: {
        primaryColor: "#69BE28",
        foregroundColor: "#000000"
      },
      languageDictionary: {
        title: "GCO TeamKeeper"
      }
    }
  );
  constructor(
    private router: Router) {
    this.userProfile = JSON.parse(localStorage.getItem('profile'));
    // Add callback for lock `authenticated` event
    this.lock.on('authenticated',  (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
      this.lock.getProfile(authResult.idToken, (error, profile) => {
        if (error) {
          alert(error);
          return;
        }
        profile.user_metadata = profile.user_metadata || {};
        localStorage.setItem('profile', JSON.stringify(profile));
        this.userProfile = profile;
        this.router.navigate(['/organization']);
      });
    })
  }
  public login() {
    // Call the show method to display the widget.
    this.lock.show();
  };
  public authenticated() {
    // Check if there's an unexpired JWT
    // It searches for an item in localStorage with key == 'id_token'
    return tokenNotExpired();
  };
  public logout() {
    // Remove token from localStorage
    localStorage.removeItem('id_token');
    localStorage.removeItem('profile');
    this.userProfile = undefined;
    this.router.navigate(['/start']);
  };
}