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

Angular 13中出现TypeError: users.filter不是函数,原因是什么?

问题原因及解决方法:TypeError: users.filter is not a function

核心原因

Firebase Realtime Database 的 ${environment.fbDbUrl}/users.json 接口返回的是键值对格式的对象,而非数组。比如返回结构通常是:

{
  "user-id-1": { "nickname": "test1", "email": "test1@example.com" },
  "user-id-2": { "nickname": "test2", "email": "test2@example.com" }
}

对象类型没有 filter 方法,直接调用就会触发 TypeError。

解决方法

修改 AuthService 中的 getByNickName 方法,先将返回的对象转换为数组,再执行筛选:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../environments/environment';

@Injectable({ providedIn: 'root' })
export class AuthService {
  constructor(private http: HttpClient) {}

  getByNickName(nickname: string): Observable<any[]> {
    return this.http.get(`${environment.fbDbUrl}/users.json`).pipe(
      // 将Firebase返回的键值对对象转为数组
      map(response => {
        if (!response) return [];
        // 遍历对象键,把每个用户数据转为数组元素,同时保留Firebase生成的ID
        return Object.keys(response).map(key => ({
          ...response[key],
          id: key
        }));
      }),
      // 现在可以正常调用filter筛选昵称匹配的用户
      map(users => users.filter(user => user.nickname === nickname))
    );
  }
}

额外验证步骤

如果不确定返回数据格式,可以先在组件中临时打印响应内容确认:

// 在RegisterComponent中临时添加
this.authService.getByNickName('test').subscribe(res => {
  console.log('原始响应:', res);
});

内容的提问来源于stack exchange,提问作者Konstantin Ershov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:24:20