2016-11-10 2 views
1

저는 학습을 위해 Angular 2 SPA를 만들고 인증을 위해 Auth0을 통합했습니다. 내 응용 프로그램의 차이점에서 호출 될 auth.service.ts가 있습니다 (예 : 로그 아웃 할 최상위 navbar 및 로그인 및 등록을 처리 할 auth-page).Auth0 서비스가 Angular 2를 사용하여 컨테이너를 찾을 수 없습니다.

나는 다음과 같은 오류가 컨테이너 옵션을 설정하여 사업부의 Auth0 컨테이너를 배치하려고 할 때 :

가 어떻게이 auth.service 어떻게 알릴 수 ID의 인증-컨테이너 요소를 찾을 수 없습니다/어디에서 auth-container div를 찾을 수 있습니까? auth.service는 잠금 변수가 사용되는 다른 위치의 다른 기능에 사용되기 때문에 auth.component.ts 안에 모든 로직을 배치하는 것은 옵션이 아닙니다. 잘

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

답변

1

그들에 의해 당신의 인생을 쉽게하지만하지 않았다

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 실수 나는 그것을 일하게 만들었다. auth.service은, 그것은을 제공하는 서비스 컨테이너의되지

auth.lock.show(); 
+0

덕분에, 완벽하게 일 :

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

그리고이 예를 완료하게 여기 내 인증 서비스 코드입니다! – Sam

0

생성자에서이 삭제

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

auth.component.ts :

이 시도 로그인 기능이 호출 될 때 팝업.

그래서 원하는 위치에서 다시 사용하려면 인증 서비스를 호출하려는 구성 요소에 인증 서비스를 주입해야합니다. 그런 다음 메서드를 호출하면됩니다. 예를 들어, 여기에 내 시작 구성 요소에 대한 html이 있습니다. 당신은 로그인의 버튼의 클릭 이벤트가 "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> 

그리고 여기 시작 구성 요소 코드 (의 주입을주의 생성자의 인증 서비스) :

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']); 
    }; 
} 
관련 문제