Home > Back-end >  Getting data from json file by ID in Angular
Getting data from json file by ID in Angular

Time:08-30

I've created an Angular app that acts like a vehicle shop. On the main page there is a CarListView component which gets all the cars from the cars.json file and displays them via the getCars() method shown below.

This is my car.service.ts

private carUrl = '/api/cars/cars.json';
  constructor(private http: HttpClient) {}

  getCars(): Observable<ICar[]> {
    return this.http.get<ICar[]>(this.carUrl).pipe(
      tap((data) => console.log('All', JSON.stringify(data))),
      catchError(this.handleError)
    );
  }

private handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred:  ${err.error.message}`;
    } else {
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
    }
    console.log(errorMessage);
    return throwError(() => errorMessage);
  }

and this is car-detail.component.ts

  pageTitle: string = 'Car Detail';
  car: ICar[] = [];
  brand: string = '';
  model: string = '';
  sub!: Subscription;
  errorMessage: string = '';

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private carService: CarService
  ) {}

  ngOnInit(): void {
    const id = Number(this.route.snapshot.paramMap.get('carId'));
    const brand = this.route.snapshot.paramMap.get('brandName');
    const model = this.route.snapshot.paramMap.get('model');
    this.pageTitle  = `:`   ' '   `${brand}`   ` - `   `${model}`;
    // this.sub = this.carService.cDeatils(id).subscribe({
    //   next: (car) => {
    //     this.car = car;
    //   },
    //   error: (err) => (this.errorMessage = err),
    // });
  }

  onBack(): void {
    this.router.navigate(['/cars']);
  }
}

So how can I get data for one specific vehicle by ID and not for all

CodePudding user response:

You can do it by using caching cars API call, using shareReplay()` operator. Kind of implementing local caching for API json call.

Then to retrieve by id you can use cars.find(car => car.id === id) get car by id.

TS

export class CarService {

  private carUrl = '/api/cars/cars.json';
  private readonly cars$ = this.http.get<ICar[]>(this.carUrl).pipe(
    shareReplay(1),
    catchError(this.handleError),
  );

  constructor(private http: HttpClient) {}

  getCars(): Observable < ICar[] > {
    return cars$;
  }

  getCarById(id: string): Observable < ICar | undefined > {
    return cars$.pipe(
      map((cars) => cars.find(car => car.id === id)),
    );
  }

  private handleError(err: HttpErrorResponse) {
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      errorMessage = `An error occurred:  ${err.error.message}`;
    } else {
      errorMessage = `Server returned code: ${err.status}, 
       error message is: ${err.message}`;
    }
    console.log(errorMessage);
    return throwError(() => errorMessage);
  }
}
  • Related