【问题标题】:Auth0 service unable to find container using Angular 2Auth0 服务无法使用 Angular 2 找到容器
【发布时间】:2017-03-24 10:56:40
【问题描述】:

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

当尝试通过设置容器选项将 Auth0 容器放置在 div 中时,我收到以下错误:Can't find element with id auth-container

如何让 auth.service 知道如何/在哪里寻找 auth-container div?将所有逻辑放在 auth.component.ts 中可能不是一种选择,因为 auth.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>

【问题讨论】:

    标签: javascript authentication angular auth0


    【解决方案1】:

    好吧,他们并没有让你的生活变得轻松,但我错误地让它发挥了作用。

    试试这个:

    auth.component.ts

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

    从你的构造函数中删除它

    auth.lock.show();
    

    【讨论】:

      【解决方案2】:

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

      所以,要在任何你喜欢的地方重用它,你需要将 auth 服务注入到你想要调用 auth 服务的组件中。然后,您只需调用该方法。例如,这是我的 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']);
        };
      }
      

      【讨论】:

        猜你喜欢
        • 2016-12-16
        • 2019-02-08
        • 2018-05-25
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 2022-12-09
        • 1970-01-01
        相关资源
        最近更新 更多