简体   繁体   中英

Displaying data from local storage

I've made a mock car-dealership app which displays a list of cars pulled from a.json file.

If the local storage item 'cars' is empty, the app shows the list of cars from the.json file, if the item is full then the page should display cars from local storage.

从 .json 中提取的汽车列表

How can I display local storage data instead of data from.json file?

car-list.component.ts

errorMessage: string = '';
sub!: Subscription;

private _listFilter: string = '';

get listFilter(): string {
   return this._listFilter;
}
set listFilter(value: string) {
   this._listFilter = value;
   this.filteredCars = this.performFilter(value);
}

filteredCars: ICar[] = [];
cars: ICar[] = [];

ngOnInit(): void {
    if (this.carService.getItem('cars')) {
      console.log('%ccar-list.component.ts line:52 yes', 'color: #007acc;');

      // this.sub = this.carService.getCarsLocal().subscribe({
      //   next: (cars) => {
      //     (this.cars = cars), (this.filteredCars = this.cars);
      //   },
      //   error: (err) => (this.errorMessage = err),
      // });
    } else {
      this.sub = this.carService.getCars().subscribe({
        next: (cars) => {
          (this.cars = cars), (this.filteredCars = this.cars);
          this.carService.setItem('cars', this.cars);
        },
        error: (err) => (this.errorMessage = err),
      });
    }
  }

ngOnDestroy(): void {
    this.sub.unsubscribe();
  }

car.service.ts

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

  formGroup: FormGroup;
  storedData: string;

  constructor(private http: HttpClient, private formBuilder: FormBuilder) {
    this.formGroup = this.formBuilder.group({
      storageKey: '',
      storageData: '',
    });
  }

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

  getCarById(id: number): Observable<ICar | undefined> {
    const savedCar: any = localStorage.getItem('id');
    if (savedCar) {
      return savedCar;
    } else {
      return this.cars$.pipe(
        map((cars) => cars.find((car) => car.carId === id))
      );
    }
  }

  public getCarsLocal() {
    let cars: any = this.getItem('cars');
    for (let i = 0; i < cars.length; i++) {}
  }

  public updateItem(key: string, data: any) {
    let cars: any = this.getItem('cars');
    for (let i = 0; i < cars.length; i++) {
      if (cars[i].carId === key) {
        cars[i] = data;
      }
    }

    this.setItem('cars', cars);
  }

  public setItem(key: string, data: any): void {
    localStorage.setItem(key, JSON.stringify(data));
  }

  public getItem(key: string): string {
    return JSON.parse(localStorage.getItem(key));
  }

  public removeItem(key): void {
    localStorage.removeItem(key);
  }

  public clear() {
    localStorage.clear();
  }

  onSetData() {
    this.setItem(
      this.formGroup.get('storageKey').value,
      this.formGroup.get('storageData').value
    );
  }

  onGetData() {
    this.storedData = this.getItem(this.formGroup.get('storageKey').value);
  }

  onRemoveData() {
    this.removeItem(this.formGroup.get('storageKey').value);
  }

  onClearData() {
    this.clear();
  }

  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);
  }
if (this.carService.getItem('cars')) {
  console.log('%ccar-list.component.ts line:52 yes', 'color: #007acc;');

  // this.sub = this.carService.getCarsLocal().subscribe({
  //   next: (cars) => {
  //     (this.cars = cars), (this.filteredCars = this.cars);
  //   },
  //   error: (err) => (this.errorMessage = err),
  // });
} else {
  this.sub = this.carService.getCars().subscribe({
    next: (cars) => {
      (this.cars = cars), (this.filteredCars = this.cars);
      this.carService.setItem('cars', this.cars);
    },
    error: (err) => (this.errorMessage = err),
  });
}

In this if-else block, I think you need to check in localStorage , but you are using this.carService .

Replacing it with localStorage.getItem('cars') should do the task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM