Angular try from local json file find by id
I have local json file (Kitchen types), i create KitchenTypesService there are 2 inside function GET AND FIND(ID), GET function its work, but not working find function, have error "ERROR TypeError: Unable to lift unknown Observable type", i try with find function get kitchen with id. Tell me what's the problem
Service
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));
}
}
Component
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');
}
}
Local 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",
}
]
Error Message
[
So there are a few ways to tackle this. You're right, HttpClient does cause the error you mentioned, but there is a way around this. May be this can help you.
Directly importing the JSON file using resolveJsonModule
To work with this, you'll need to add the following in your tsconfig.json file
"resolveJsonModule": true
Then you can simply import your data by adding this in your service:
import * as data from './kitchenTypes.json'
Note that your will need to update the file path accordingly
Once this is done, you can now access the JSON file data. You can view, and search the contents of the JSON file as per your need.
data: any = (data as any).default;