0
votes

On my app i'm setting an auth service. Pretty simple behavior.

appComponent contains a simple button for login through Google with event (click)='login'. After i accept, I want to redirect my user to /account.

The app works as expected BUT i encounter an error on ng serve:

[default] C:\Project\src\app\app.component.ts:24:8

 Property 'then' does not exist on type 'void'.

[default] C:\Project\src\app\services\auth.service.ts:28:22

These errors appears to be non blocking, since the app appears to work properly. Do you have any idea of how to solve them?

I guess the problem seems to appear because i apply then on the returned _auth.login() result which is the angularfire auth login method WHICH returns a promise... But i don't know how i can refactor my code to call the service properly if it's indeed the problem. I think (correct me if I'm wrong) it's a bad idea to call redirect from the service itself.

Here are my files.

app.component.ts:

constructor(private router: Router, private _auth: AuthService) {
    this.date = new Date();
}

login() {
    this._auth.login()
    .then(() => {
        this.router.navigate(['/account']);
    });
}

logout() {
    this._auth.logout()
    .then(() => {
        this.router.navigate(['/login']);
    });
}

My AuthService:

import { Injectable } from '@angular/core';
import { AngularFire, AuthProviders } from 'angularfire2';
@Injectable()
export class AuthService {
    user = {};
    isAuthenticated: boolean = false;

    constructor(public af: AngularFire) {
        this.af.auth.subscribe(user => {
        if (user && !user.auth.isAnonymous) {
            this.user = user;
            this.isAuthenticated = true;
            console.log('User Logged in', user, this.getUserEmail());
        } else {
            this.user = {};
            this.isAuthenticated = false;
            console.log('User Not Authenticated', user);
        }
        });
    }

    getUser() {
        return this.user;
    }

    getUserEmail() {
        return this.user.auth.email;
    }

    login() {
        return this.af.auth.login({
        provider: AuthProviders.Google
        });
    }

    logout() {
        return this.af.auth.logout();
    }
}

Do you have any example of an authservice using AF properly?

1

1 Answers

1
votes

AngularFire2's logout method doesn't return a Promise:

public logout(): void {
  this._authBackend.unauth();
}

There is an unmerged PR to have logout return a Promise, but at the moment, it doesn't.

You could either change your app.component.ts code to:

logout() {
    this._auth.logout();
    this.router.navigate(['/login']);
}

Or you could change your AuthService to:

logout() {
    this.af.auth.logout();
    return Promise.resolve();
}

Either way, you will need to watch to see if/when the PR is merged.