With the help of the API, I get the data and get 20 objects. I display these elements on the page and each element has a button. I need a certain object to be displayed when I click, but unfortunately I only get the first object and I also get an error that points to .find((element) => element.id === id) and says:
TS2367: This condition will always return 'false' since the
types 'number' and 'ProductModel' have no overlap.
and second error:
this.productDifferent`: `Type 'ProductModel | undefined' is not assignable to type 'ProductModel'.
Type 'undefined' is not assignable to type 'ProductModel'.`
How to get clickable object on which I click?
Component.ts
@Component({
selector: 'app-products-list-api',
templateUrl: './products-list-api.component.html',
styleUrls: ['./products-list-api.component.css']
})
export class ProductsListApiComponent implements OnInit {
products: ProductModel[];
productDifferent: ProductModel;
constructor(private apiService: ApiService) {}
ngOnInit(): void {
this.apiService.getAllProducts().subscribe((value) => {
this.products = value
});
}
addProductToList(id: ProductModel) {
this.productDifferent = this.products.find((element) => element.id === id);
}
}
Component.html
<div>
<div *ngFor="let product of products">
<p> {{product.id}} {{product.title}} {{product.price}}
<button (click)="addProductToList(product)"> Add to products list </button>
<p>
</div>
</div>
ProductModel.ts
export interface ProductModel {
id: number;
title: string;
price: number;
}
Service
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private httpClient: HttpClient) {}
getAllProducts(): Observable<ProductModel[]> {
return this.httpClient.get<ProductModel[]>('https://fakestoreapi.com/products');
}
}