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

Angular过滤Observable<TechTag[]>遇类型错误,求子串匹配方案

正确实现Angular中按子串过滤TechTag数组的Observable方法

基础定义

TechTag类

export class TechTag {
    id?: number;
    tagName!: string;
}

服务基础函数

getAllTechTags(): Observable<TechTag[]> {
    return this.http.get<TechTag[]>(this.baseUrl); // baseUrl指向"../assets/techTags.json"
}

JSON数据示例

[
  {
    "id": 1,
    "tagName": ".net"
  },
  {
    "id": 2,
    "tagName": "html"
  },
  {
    "id": 3,
    "tagName": "javascript"
  },
  {
    "id": 4,
    "tagName": "css"
  },
  {
    "id": 5,
    "tagName": "php"
  },
  {
    "id": 8,
    "tagName": "c"
  },
  {
    "id": 9,
    "tagName": "c#"
  },
  {
    "id": 10,
    "tagName": "c++"
  }
]

组件校验代码

ngOnInit(): void {
    let techTags: TechTag[];
    this.techTagsService.searchTechTags("java").subscribe({
        next: (response => {
          techTags = response;
        }),
        complete: () => {
          console.log(techTags);
        }
      }
    );
}

之前尝试的问题分析

  • 尝试1:使用==做完全匹配,不符合子串包含的需求,仅能返回与关键词完全一致的项。
  • 尝试2:匹配逻辑倒置,用tagName.includes(tags.tagName)检查的是关键词是否包含标签名,而非标签名包含关键词,导致返回"j"、"ava"这类反向匹配项,漏掉目标项"javascript"。
  • 尝试3/4:报错includes/indexOf is not a function,说明部分tagName并非字符串类型(可能JSON中存在null/undefined或数字值),类型断言后实际数据不匹配。

正确实现方案

核心解决类型安全和匹配逻辑两个问题,同时兼容异常数据:

方案1:独立实现搜索函数

searchTechTags(tagName: string): Observable<TechTag[]> {
    // 统一转为小写实现大小写不敏感匹配(可根据需求移除)
    const searchTerm = tagName.toLowerCase();
    return this.http.get<TechTag[]>(this.baseUrl).pipe(
        map(data => 
            data.filter(tag => 
                // 先确保tagName是字符串,避免类型错误
                typeof tag.tagName === 'string' && 
                tag.tagName.toLowerCase().includes(searchTerm)
            )
        )
    );
}

方案2:复用已有的getAllTechTags函数

searchTechTags(tagName: string): Observable<TechTag[]> {
    const searchTerm = tagName.toLowerCase();
    return this.getAllTechTags().pipe(
        map(data => 
            data.filter(tag => 
                typeof tag.tagName === 'string' && 
                tag.tagName.toLowerCase().includes(searchTerm)
            )
        )
    );
}

关键说明

  1. 类型校验:通过typeof tag.tagName === 'string'规避非字符串值调用字符串方法的报错。
  2. 大小写兼容:将搜索词和标签名统一转小写,确保匹配不受大小写影响(如"Java"也能匹配"javascript"),若需严格区分大小写,移除.toLowerCase()即可。
  3. 正确匹配逻辑:tag.tagName.includes(searchTerm)实现标签名包含搜索子串的需求。

预期测试结果

以"java"为搜索参数时,将返回:

[
    {
        "id": 3,
        "tagName": "javascript"
    },
    {
        "id": 17,
        "tagName": "java"
    }
]

内容的提问来源于stack exchange,提问作者Arturo Lozano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:50:43