检查登录用户时,共享服务变量未定义

时间:2019-01-09 14:39:10

标签: angular typescript firebase firebase-authentication

我打算检查用户是否已登录,该信息应在整个应用程序中可用。

为此,我在共享服务文件 user.service.ts

中使用了此代码
import { Injectable } from '@angular/core';
import * as firebase from 'firebase/app';
import 'firebase/auth';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  public loggedIn:boolean;

  constructor() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.loggedIn=true;
      } else {
        this.loggedIn=false;
      }
    });
  }
}

然后我将该服务注入导航栏组件

(navigation-bar.component.ts)

import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
import { Router } from '@angular/router';

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

  isLoggedIn$ = this.userService.isLoggedIn;

  constructor(private userService:UserService, private router:Router) {
  }

  ngOnInit() {
  }

}

(navigation-bar.component.html)

<li class="nav-item px-2">
  <button type="button" (click)="login()" class="btn btn-info">{{ 
userService.loggedIn===undefined?'undefined':userService.loggedIn }} 
</button>
</li>
<li *ngIf="!userService.loggedIn" class="nav-item px-2">
  <button type="button" (click)="login()" class="btn btn- 
info">Login</button>
 </li>
<li *ngIf="userService.loggedIn" class="nav-item px-2">
  <button type="button" (click)="logout()" class="btn btn-info">Log 
out</button>
</li>

userService.loggedIn变量为undefined,我希望它根据用户是否登录来显示true或false。

1 个答案:

答案 0 :(得分:4)

直到完成firebase.auth().onAuthStateChanged可观察性时才定义。您可以将loggedIn设置为BehaviorSubject<boolean>,然后使用async管道来获取值。像这样:

export class UserService {

  private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject(false);
  public isLoggedIn = this.loggedIn.asObservable();


  constructor() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.loggedIn.next(true);
      } else {
        this.loggedIn.next(false);
      }
    });
  }
}

在组件.ts中:

isLoggedIn$ = this.userService.isLoggedIn;
constructor(private userService:UserService) {}

.html中:

<li *ngIf="!isLoggedIn$ | async" /* ... */>
  ...
</li>