0

I'm building an Angular2 app using Auth0 for authentication and AngularFire for my database. In my constructor, I passed my AngularFire af instance, but I can't access it inside my callback event. Is there another way to access my AngularFire instance?

// app/auth.service.ts

import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { AngularFire, AuthMethods, AuthProviders } from 'angularfire2';


// Avoid name not found warnings
declare var Auth0Lock: any;
declare var Auth0: any;

@Injectable()
export class Auth {
 // Configure Auth0
  lock = new Auth0Lock('AUTH0_CLIENT_ID', 'AUTH0_DOMAIN', {});


  constructor(private af: AngularFire) {
    // Add callback for lock `authenticated` event

    this.lock.on("authenticated", (authResult) => {
      this.lock.getProfile(authResult.idToken, function(error:any, profile:any){
        if(error){
          throw new Error(error);
        }

        localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('profile', JSON.stringify(profile));

        var options = {
        id_token : authResult.idToken,
        api : 'firebase',
        scope : 'openid name email displayName',
        target: 'AUTH0_CLIENT_ID'
        };


        var auth0 = new Auth0({domain:'AUTH0_DOMAIN', clientID:'AUTH0_CLIENT_ID' });
        auth0.getDelegationToken(options, function(err, result){

          if(!err){


            this.af.auth.login(result.id_token, {
              provider: AuthProviders.Custom,
              method: AuthMethods.CustomToken
            });
            console.log(result);
          }
        });
      });
    });
  }
}

1 Answer 1

7

That's because your this inside callback function points to that function. You have three options:

  1. Save this of class: let that = this and use that.af inside callback.
  2. Use lambda, because it doesn't change this: (error, profile) => {...}
  3. You can call .bindTo(this) to function and bind this to class

Also, I recommend lambda approach.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I spent days trying to figure out what the issue was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.