You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular结合Firebase开发时当前用户名及下拉菜单不显示问题排查

问题原因&修复方案

核心问题是变量名不匹配:你在BsNavbarComponent中把afAuth.authState赋值给了currentUser变量,但模板里*ngIf绑定的是从未被赋值的currentUser$,async管道永远拿到空值,自然不会渲染下拉菜单。
另外还有两个影响下拉交互的小问题:

  1. 使用ng-bootstrap的Dropdown组件时不需要加原生bootstrap的data-toggle属性,二者会冲突
  2. 下拉触发按钮的类名写错,多了空格,应该是dropdown-toggle而非dropdown toggle
  3. 冗余的未赋值placement属性也会影响组件初始化

修复后的Navbar.component.ts代码

import { Component, OnInit } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';
import { Observable } from 'rxjs/Observable'

@Component({
  selector: 'bs-navbar',
  templateUrl: './bs-navbar.component.html',
  styleUrls: ['./bs-navbar.component.css']
})
export class BsNavbarComponent  {
  // 直接给模板用到的currentUser$赋值
  currentUser$: Observable<firebase.User | null> = this.afAuth.authState;

  constructor(private afAuth: AngularFireAuth) { }
  

  logout() {
    this.afAuth.signOut(); 
  }

}

修复后的navbar.component.html下拉部分代码

<!-- 其余导航代码保持不变,仅修改下拉相关的li标签部分 -->
<li ngbDropdown *ngIf="currentUser$ | async as user; else anonymousUser" class="nav-item dropdown">
    <a ngbDropdownToggle class="nav-link dropdown-toggle" id="dropdown01" aria-haspopup="true" aria-expanded="false">{{ user.displayName }}</a> 
    <div ngbDropdownMenu class="dropdown-menu" aria-labelledby="dropdown01">
        <a ngbDropdownItem class="dropdown-item" routerLink="/admin/houses">My Houses</a>
        <a ngbDropdownItem class="dropdown-item" (click)="logout()"> Log out</a>
    </div>
</li>

内容的提问来源于stack exchange,提问作者Dorcas Osadare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:45:05