First of all, to avoid closure of this question, I am aware that this question has a very similar title here:
Property '...' has no initializer and is not definitely assigned in the constructor
But, the biggest problem is that it was asked 5 years ago, and most of the answers are directed to TypeScript Version 2.9.
I am facing the same error message, but in Angular 16 - Which uses TypeScript 4.9.
I tried the answers and solutions in the question above, but they did not work for me, in my Angular Component.
The problem I am having is that I want to declare a variable that will be a array of a specific object type inside my Class component.
This is what I tried so far, using the suggestions from the other answer above, by @Sajeetharan:
// Interface
export interface PhotosApi {
albumId?: number;
id?: number;
title?: string;
url?: string;
thumbnailUrl?: string;
}
And this is my component:
import {Component, OnInit} from '@angular/core';
// Importar o cliente para fazer os requests na API
import { HttpClient } from '@angular/common/http';
import { throwError } from 'rxjs';
// Importar a Interface do Slide
import { PhotosApi } from "./interfaces/photos-api";
@Component({
selector: 'app-row-clients',
templateUrl: './row-clients.component.html',
styleUrls: ['./row-clients.component.css']
})
// Exportar a Classe que vai ser o Template da Row Componentes
export class RowClientsComponent implements OnInit {
limit: number = 10; // <==== Number of API results
// Sessão de construtor da request da API
constructor(
private readonly http: HttpClient, private apiData: PhotosApi
) {
// @Sajeetharan's solution
this.apiData: PhotosApi = [];
}
ngOnInit() {
this.fetch()
}
// Mapear os objetos do tipo PhotosApi para a apiData
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)
)
}
}
It is not working. It throws a error inside the constructor. Before, I was trying to initialize it like this:
export class RowClientsComponent implements OnInit {
apiData: PhotosApi;
// Etc...
Which throws the error in the title, and also mentioned on that other question.
I am basing my component using the following StackBlitz tutorial, which does not work and also causes errors.
The "any[]" does remove the error but as I specified before, it will be a array of object type PhotosApi - Just like in Java that we can create arrays of specific and defined objects (Something like ArrayList).
I appreciate any help
Edit 1: I changed the code to achieve the logic "This is a empty array of PhotosApi objects that will be populated later with PhotosApi objects."
This is the new Export Class, I added comments on what changed:
// Export my class which will be my Angular component
export class RowClientsComponent {
limit: number = 10; // <==== Number of API results
// Sessão de construtor da request da API
constructor(
private readonly http: HttpClient, private apiData: PhotosApi[]
) {
// @Sajeetharan's solution -- Now there is no more errors in the code IDE.
this.apiData = []
}
ngOnInit() {
this.fetch()
}
// Map objects of type PhotosApi into apiData array.
fetch() {
const api = `https://jsonplaceholder.typicode.com/albums/1/photos?_start=0&_limit=${this.limit}`;
const http$ = this.http.get<PhotosApi>(api);
// Now, here, on IDE I've been seeing two errors:
// TS2322: Type 'PhotosApi' is not assignable to type 'PhotosApi[]'.
// TS2740: Type 'PhotosApi' is missing the following properties from type 'PhotosApi[]': length, pop, push, concat, and 29 more
http$.subscribe(
res => this.apiData = res,
err => throwError(err)
)
}
}
And, this is what the compiler shows me:
Edit 2: Tried following the syntax on this answer specifically, alongside what @JaredSmith told me, like this:
Way #1
// Export my class which will be my Angular component
export class RowClientsComponent {
limit: number = 10; // <==== Number of API results
// Array of Objects - The equals signs tells: Initialize the Array of Objects when declaring it.
apiData: PhotosApi[] = Array<PhotosApi>;
Way #2
// Array of Objects - The equals signs tells: Initialize the Array of Objects when declaring it.
apiData: PhotosApi[] = PhotosApi[];
And in both methods I got TS2693: 'PhotosApi' only refers to a type, but is being used as a value here.