AngularFire.auth不会发出任何值

时间:2016-10-25 18:39:19

标签: angular firebase firebase-authentication rxjs angularfire2

我在Angular2中建立一个AuthService,并且在广播身份验证方面存在一些问题...

似乎this.af.auth.subscribe没有发出任何东西......

import {Injectable, OnInit, OnDestroy} from '@angular/core';
import {Http} from "@angular/http";
import {Router} from "@angular/router";
import {JwtHelper} from "angular2-jwt/angular2-jwt";
import {AngularFire, AngularFireAuth, AuthProviders, AuthMethods} from "angularfire2";
import {environment} from "../environments/environment";
import {Subject, Subscription} from "rxjs";
import {Output} from "@angular/core/src/metadata/directives";

@Injectable()
export class AuthService implements OnInit, OnDestroy{
    @Output() public loginStatus$ = new Subject<LoginStatus>();
    private auth$:Subscription;

    ngOnInit(): void {
        this.auth$ = this.af.auth.subscribe(user => {
                console.log(user);
                if (user)
                    this.loginStatus$.next(new LoginStatus(true,"Login successful", this.getDecodedJwt()));
                else if (!user && this.getDecodedJwt())
                    this.loginStatus$.next(new LoginStatus(false,"Could not login to real-time database!"));
                else
                    this.loginStatus$.next(new LoginStatus(false,"Logged out."));
            },
            error => console.log(error))
    }

    constructor(
        private http:Http,
        private router:Router,
        private jwtHelper: JwtHelper,
        private af: AngularFire,
        private auth: AngularFireAuth,
    ) {}

    ngOnDestroy(): void {
        this.auth$.unsubscribe();
        this.loginStatus$.complete();
    }



    login(login:LoginBody) {
        this.http.post(environment.baseUri + "auth/login_check", login)
            .subscribe(
                response => {
                    localStorage.setItem("auth_token",response.json().token);
                    this.auth.login(response.json().token, {
                        provider: AuthProviders.Custom,
                        method: AuthMethods.CustomToken
                    });},
                error => {
                    console.log(error);
                    switch (error.status){
                        case 403:this.loginStatus$.next(new LoginStatus(false,"Password does not match the supplied email address.", error)); break;
                        case 404:this.loginStatus$.next(new LoginStatus(false,"Unknown username or password.", error));break;
                        default: this.loginStatus$.next(new LoginStatus(false,"Server error. We are working on a solution, please try again later.", error));break;
                    }
                });

        return this.loginStatus$;
    }

    logout() {
        localStorage.removeItem("auth_token");
        this.af.auth.logout();
        this.router.navigateByUrl("");
    }



    hasRole(role:string){
        if (!this.isLoggedIn())
            return false;

        const jwt = this.getDecodedJwt();
        for (let i = 0; i < jwt.claims.roles.length;i++)
        {
            if (role.toUpperCase() === jwt.claims.roles[i].toUpperCase())
                return true;
        }

        return false;
    }

    private getDecodedJwt() {
        return this.jwtHelper.decodeToken(localStorage.getItem("auth_token"));
    }

    isLoggedIn() {
        return !!localStorage.getItem("auth_token");
    }
}

export class LoginBody {
    constructor(
        public _username: string,
        public _password: string
    ){}
}

export class LoginStatus {
    constructor(public status: boolean, public message: string, public token: any = []) {}
}

我的LoginComponent中使用了AuthService:

login(form) {
    this.loginStatus$ = this.authService.login(form.value)
        .subscribe(status => console.log(status));
}

所有请求都有效......用户确实从我的服务器获取了JWT令牌,并且他确实登录了Firebase(来自网络选项卡)。

1 个答案:

答案 0 :(得分:0)

好的,obvoius的回答是@Injectable不支持OnInit / OnDestroy,所以y订阅永远不会被设置。