Angular 尝试从本地 json 文件中按 id 查找

Angular try from local json file find by id

我有本地 json 文件(厨房类型),我创建了 KitchenTypesService,其中有 2 个内部函数 GET 和 FIND(ID),GET 函数正常工作,但查找函数不工作,出现错误“ERROR TypeError : Unable to lift unknown Observable type”,我尝试使用查找功能获取带有 id 的厨房。告诉我有什么问题

服务

export class KitchenTypesService {
  private _jsonURL = 'assets/data/kitchenTypes.json';
  constructor(private http: HttpClient) {
    this.get().subscribe((data) => data);
  }

  public get(): Observable<any> {
    return this.http.get(this._jsonURL);
  }

  public find(id: number) {
    this.get().subscribe(find((data: any) => data.id == id));
  }
}

组件

export class KitchenDimensionComponent implements OnInit {
  title: string = 'Virtuvės matmenys';
  step: number = 2;
  selectedKitchenId: number;
  kitchen: any;
  constructor(
    private persistenceService: PersistenceService,
    private httpKitchenTypes: KitchenTypesService
  ) {}

  ngOnInit(): void {
    this.initialSelectedKitchenId();
    console.log(this.httpKitchenTypes.find(1));
  }

  initialSelectedKitchenId(): void {
    this.selectedKitchenId = this.persistenceService.get('selectedKitchenId');
  }
}

本地KitcehTypes.json

[
  {
    "id": 1,
    "title": "Standartine",
    "src": "/assets/images/kitchen-types/one-well.png",
  },

  {
    "id": 2,
    "title": "L forma",
    "src": "/assets/images/kitchen-types/L-shaped.png",
  },

  {
    "id": 3,
    "title": "U forma",
    "src": "/assets/images/kitchen-types/U-shaped.png",
  },

  {
    "id": 4,
    "title": "G forma",
    "src": "/assets/images/kitchen-types/G-shaped.png",
  }
]

错误信息

[

所以有几种方法可以解决这个问题。没错,HttpClient 确实会导致您提到的错误,但有一种解决方法。也许这可以帮助你。

使用 resolveJsonModule
直接导入 JSON 文件要处理此问题,您需要在 tsconfig.json 文件

"resolveJsonModule": true
然后您可以通过在您的服务中添加以下内容来简单地导入您的数据:

import * as data from './kitchenTypes.json'

请注意,您需要相应地更新文件路径

完成后,您现在可以访问 JSON 文件数据。您可以根据需要查看和搜索 JSON 文件的内容。

data: any = (data as any).default;