Sam Sam - 1 month ago 20
Javascript Question

Auth0 service unable to find container using Angular 2

I'm creating an Angular 2 SPA for learning purposes and integrating Auth0 for handeling the authentication. I have an auth.service.ts that is going to be called from difference places in my application, for example in the top-navbar to logout and on the auth-page to handle logins and registrations.

When trying to place the Auth0 container in a div by setting the container option I get the following error: Can't find element with id auth-container

How can I let the auth.service know how/where to look for the auth-container div? Placing all the logic inside the auth.component.ts is assumably not an option because the auth.service will be used for other functionality in other places where the lock variable is also used.

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>

Answer

Well they did not make your life easy but by mistake I made it work.

Try this:

auth.component.ts

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

Delete this from your constructor

auth.lock.show();