I want to address an issue with a similar question title that was asked 5 years ago on Stack Overflow. The problem is related to declaring a variable as an array of a specific object type in an Angular component using TypeScript 4.9.
Even though I tried the solutions provided in the older question, they did not work for me in my Angular Component. Here is what I have attempted so far:
// Interface
export interface PhotosApi {
albumId?: number;
id?: number;
title?: string;
url?: string;
thumbnailUrl?: string;
}
And here is my component code:
import {Component, OnInit} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { throwError } from 'rxjs';
import { PhotosApi } from "./interfaces/photos-api";
@Component({
selector: 'app-row-clients',
templateUrl: './row-clients.component.html',
styleUrls: ['./row-clients.component.css']
})
export class RowClientsComponent implements OnInit {
limit: number = 10;
constructor(
private readonly http: HttpClient, private apiData: PhotosApi[]
) {
this.apiData = [];
}
ngOnInit() {
this.fetch()
}
fetch() {
const api = `https://jsonplaceholder.typicode.com/albums/1/photos?_start=0&_limit=${this.limit}`;
const http$ = this.http.get<PhotosApi>(api);
http$.subscribe(
res => this.apiData = res,
err => throwError(err)
)
}
}
Despite making changes and following suggestions, the error persists inside the constructor. I also explored different ways of initializing the array but encountered new issues. Your assistance would be highly appreciated.
Edit 1: After some modifications, the errors in IDE are no longer present. I am now aiming to populate an empty array of PhotosApi objects later.
// Export my class which will be my Angular component
export class RowClientsComponent {
limit: number = 10;
constructor(
private readonly http: HttpClient, private apiData: PhotosApi[]
) {
this.apiData = []
}
ngOnInit() {
this.fetch()
}
fetch() {
const api = `https://jsonplaceholder.typicode.com/albums/1/photos?_start=0&_limit=${this.limit}`;
const http$ = this.http.get<PhotosApi>(api);
http$.subscribe(
res => this.apiData = res,
err => throwError(err)
)
}
}
The compiler shows some warnings indicating possible issues with the type definition.
Edit 2: I tried various syntax formats suggested by the community members, but encountered another error stating 'PhotosApi' only refers to a type, not a value.