Angular 2 - Angularfire 2身份验证状态

时间:2016-10-26 13:04:31

标签: angular firebase firebase-authentication angularfire2

我迷失在可观察,承诺和状态的疯狂中。我需要帮助来解决这个问题。

我尝试使用Angularfire2模块在angular 2应用程序中实现注册/登录/注册功能。我从登录功能开始。我掌握了基础知识。我可以登录并重定向到新页面。到现在为止还挺好。在我的模板中,我要检查用户是否已登录。这里开始麻烦了。我很难检查当前用户是否已登录。

Login.components.ts

import { Component, OnInit } from '@angular/core';
import {Validators, FormGroup, FormBuilder } from '@angular/forms';
import { AuthService } from '../auth.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  form: FormGroup;
  error = false;
  errorMessage = '';

  constructor(private fb:FormBuilder, private authService:AuthService, private router:Router) {}

  ngOnInit() {
     this.form = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  onLogin() {
    this.authService.loginUser(this.form.value.email, this.form.value.password)
    .subscribe(
      () => this.router.navigate(['/'])
    )
  }

}

Auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import {FirebaseAuth} from 'angularfire2/index';
import {Observable, Subject} from 'rxjs/Rx';

@Injectable()
export class AuthService {

  constructor(private auth: FirebaseAuth, private router:Router) { }

  loginUser(email, password):Observable<any> {
   return this.fromFirebaseAuthPromise(this.auth.login({email,password}));
  }

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

  fromFirebaseAuthPromise(promise):Observable<any> {
    const subject = new Subject<any>();
    promise
      .then(res => {
        subject.next(res);
        subject.complete();
      },
      err => {
        subject.error(err);
        subject.complete();
      });
    return subject.asObservable();
  }


  isAuthenticated(): Observable<any> {
      const state = new Subject<any>();

      this.auth.subscribe( (user) => {
        if (user) {
          var uid = user.uid;
          console.log('the user id:' + uid)
          state.next(true)
        } else {
          console.log("no user")
          state.next(false)
        }
      })

    return state.asObservable();
  } 
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth/auth.service';
import { AuthInfo } from './auth/auth-info';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  isAuthenticated = false;

  constructor(private authService:AuthService) {
    this.authService.isAuthenticated().subscribe(
        authStatus => this.isAuthenticated = authStatus
    );
   console.log('isAuthenticated:' + this.isAuthenticated);
   }

  isAuth() {
      return this.isAuthenticated;
  }

  onLogout() {
    this.authService.logout();
  }

  ngOnInit() {

  }
}

home.component.html

<h2>
  Please login or register to use the app
</h2>

<a [routerLink]="['/login']" *ngIf="!isAuth()">Login here</a>
<a [routerLink]="['/register']" *ngIf="!isAuth()">Register here</a>

<a *ngIf="isAuth()" (click)="onLogout()" style="cursor: pointer;">Logout</a>

登录时查看我的控制台时,我看到以下结果。

{  
  the user: id:qqsrQHB0SyeIQTbri6sYEyTTE9r2
  isAuthenticated: false
}

所以我想登录一定要成功吧?但是当我检查验证是否为真时似乎失败了。 * ngIf =&#34;!isAuth()&#34;只有在浏览器中进行了硬刷新时,HomeComponent中的{ the user: id:qqsrQHB0SyeIQTbri6sYEyTTE9r2 isAuthenticated: false } 才起作用。

经过硬刷新后,我仍然在控制台中看到:

import os
import time
import datetime

current_time = datetime.datetime.strftime(datetime.datetime.now(), '%d-  %m-%Y %H:%M:%S')
try:
    import wx
except ImportError:
    raise ImportError, "The wxPython module is required to run this   program."

class simpleapp_wx(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(500, 300))
        self.SetBackgroundColour(wx.BLUE)
        self.parent = parent
        self.initialize()

    def initialize(self):
        sizer = wx.GridBagSizer()
        font = wx.Font(20, wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
        self.SetFont(font)

        self.label = wx.StaticText(self, -1, label=u'Time Updated - 1:  {}'.format(current_time))
        self.label2 = wx.StaticText(self, -1, label=u'Time Updated - 2:  {}'.format(current_time))
        self.label.SetBackgroundColour(wx.BLUE)
        self.label.SetForegroundColour(wx.WHITE)
        self.label.SetBackgroundColour(wx.BLUE)
        self.label2.SetForegroundColour(wx.WHITE)
        sizer.Add(self.label, (4, 0), (1, 5), wx.EXPAND)
        sizer.Add(self.label2, (5, 0), (1, 5), wx.EXPAND)
        self.on_timer()
        self.on_timer2()

        self.SetSizer(sizer)
        self.Show(True)

    def on_timer(self):
        current_time = datetime.datetime.strftime(datetime.datetime.now(), '%d-%m-%Y %H:%M:%S')
        self.label.SetLabel(label=u'Time Updated -1 : {}'.format(current_time))
        wx.CallLater(1000, self.on_timer)

    def on_timer2(self):
        current_time = datetime.datetime.strftime(datetime.datetime.now(), '%d-%m-%Y %H:%M:%S')
        self.label2.SetLabel(label=u'Time Updated -2 : {}'.format(current_time))
        wx.CallLater(1000, self.on_timer2)

if __name__ == "__main__":
    app = wx.App()
    frame = simpleapp_wx(None, -1, 'Rain Sensor')
    app.MainLoop()

1 个答案:

答案 0 :(得分:7)

你这么复杂,你的代码应该是这样的:

<强> Auth.service

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { FirebaseAuth } from 'angularfire2/index';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class AuthService {

  constructor(private auth: FirebaseAuth, private router:Router) { }

  loginUser(email, password) {
    return this.auth.login({email,password}) //angularfire returns a promise
  }

  loginUserObservable(email,password){ //but if still want to use an observable
    return Observable.fromPromise(<Promise<any>> this.auth.login({email,password})) // we need to cast the Promise because for some reason Angularfire returns firebase.Promise
  }

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

  isAuthenticated(): Observable<any> {
      return this.auth; //auth is already an observable
  } 
}

<强> home.component.ts:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { AuthService } from './auth/auth.service';
import { AuthInfo } from './auth/auth-info';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
  private sub: Subscription;

  constructor(private authService:AuthService) { }

  ngOnInit() {
    this.sub = this.authService.isAuthenticated().subscribe(authResp => 
      console.log('isAuthenticated: ', authResp);
    );
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

  isAuth() {
      return this.authService.isAuthenticated();
  }

  onLogout() {
    this.authService.logout();
  }
}

<强> home.component.html

<h2>
  Please login or register to use the app
</h2>

<a [routerLink]="['/login']" *ngIf="!(isAuth() | async)">Login here</a>
<a [routerLink]="['/register']" *ngIf="!(authService.isAuthenticated() | async)">Register here</a>
<!--you can either use !(isAuth() | async) or !(authService.isAuthenticated() | async) it's up to your religion -->

<a *ngIf="isAuth() | async" (click)="onLogout()" style="cursor: pointer;">Logout</a>

我建议你阅读simple guide