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

Auth0 service unable to find container using Angular 2

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

当尝试通过设置容器选项将 Auth0 容器放入 div 时,出现以下错误:找不到 ID 为 auth-container

的元素

如何让 auth.service 知道 how/where 寻找身份验证容器 div?将所有逻辑放在 auth.component.ts 中可能不是一个选项,因为 auth.service 将用于其他也使用锁定变量的地方的其他功能。

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();

auth.service不是容器,它是调用登录功能时提供弹出窗口的服务。

因此,要在任何地方重用它,您需要将身份验证服务注入到要从中调用身份验证服务的组件中。然后,您只需调用该方法。例如,这是我的 Start 组件的 html。可以看到登录按钮的点击事件绑定到组件(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']);
  };
}