The property '.....' is missing an initializer and has not been explicitly assigned in the constructor

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.

Answer №1

Make sure to properly define your arrays of PhotosApi objects. It appears that you are mixing up where you declare your types and where you initialize a value.

You have attempted the following:

apiData: PhotosApi[] = PhotosApi[];
//or
apiData: PhotosApi[] = Array<PhotosApi>;

However, both of these contain invalid syntax. You are duplicating the type when initializing the value, which is incorrect. The correct way is:

apiData: PhotosApi[] = [];
//or
apiData: Array<PhotosApi> = [];

In general, you only specify a type between the : and the = symbols. There are alternative methods to define or enforce types, but they are not necessary in this context.


Additionally, you have:

this.http.get<PhotosApi>(api)

This indicates that you are anticipating a single PhotosApi to be returned, however, you likely want an array instead. It should probably be corrected to:

this.http.get<PhotosApi[]>(api)

Answer №2

To achieve the desired result, follow these steps:

export class RowClientsComponent implements OnInit {
  limit = 10; // The type declaration is not necessary here as it is automatically inferred from the assigned value
  apiDate: Array<PhotosApi> = []; // Specify the type of contents in the array and initialize it with an empty array
  constructor(private readonly http: HttpClient) {}
  // Add any required additional code here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

Issue with React useCallback not being triggered upon a change in its dependencies

useCallback seems to be capturing the wrong value of its dependency each time. const [state, setState] = React.useState(0); const callback = React.useCallback(() => { console.log(state); // always prints 0, why? }, [state]); React.useEffec ...

Issue encountered in ../../../../ Unable to locate namespace 'Sizzle'

Following the execution of npm install @types/jquery, I encountered a compilation issue while running my Angular project with ng serve ERROR in ../../../../../../AppData/Roaming/JetBrains/WebStorm2020.1/javascript/extLibs/global-types/node_modules/@types/j ...

Issue with Master Toggle functionality for checkbox within expanded rows of Mat-Table does not function correctly

I'm facing an issue with my multi-row expandable mat table grid where the master toggle for inner grid checkboxes is not working. Each row fetches data from different APIs on click, and I have a checkbox selection in every row for the inner grid. Int ...

Show details when clicked with various elements

I have a dilemma with my Angular version 7 project. In a div, I have placed 6 buttons in 2 columns and I want to show a description of one button only when it is clicked. Currently, the description for all buttons displays at once upon clicking any button. ...

Exploring the process of dynamically incorporating headers into requests within react-admin

Currently utilizing react-admin with a data provider of simpleRestProvider. I am in need of a solution to dynamically add headers to requests based on user interactions. Is there a way to achieve this? Appreciate any assistance. Thank you! ...

What is the best way to assign a type based on a variadic type in TypeScript?

TypeScript playground link For my current project, I am designing a custom route handler creator for Express. The goal is to allow passing arbitrary assertions as initial arguments before invoking the route handler callback. Here's an example of how ...

What is the process for transferring files from a NodeJS website to Azure CDN?

I am searching for a solution to upload images directly to Azure CDN. Here is the situation: My client Portal built with Angular (4.x) enables users to manage their website, and they need the capability to upload images that will be displayed on the sit ...

Tips for organizing JSON data from a multiselect form

I am currently working on a template driven form with a multiselect field named assets. My framework of choice is semantic UI. <div ngModelGroup="assets"> <div class="field"> <label for="resourceName">Assets</label ...

Utilize the datasource.filter method within an *ngFor loop

I have a table that filters based on certain search criteria, which I implemented using the example found at: https://material.angular.io/components/table/examples Now, I am wondering if it is possible to apply this filtering functionality to an *ngFor lo ...

The floating filter in ag-Grid for Angular features a dropdown menu styled with Bootstrap

In my ag-grid table, I have a Bootstrap dropDownMenu displayed in CELL and in FLOATING FILTER. The issue arises when the dropdown menu is triggered - it gets hidden in the cell, as shown in the picture. https://i.sstatic.net/xBsPf.png To fix this proble ...

Ensure that the injected service's constructor has completed before running tests in Karma 4 with Angular 7

I'm including a service in this manner: it('test name', inject([ Service], (hcs: Service) => { const pipe = new MyPipe(hcs); const expectedResult = ... //The constructor of the hcs-service must be completed before executing t ...

Is it possible to integrate Firebase Storage into a TypeScript/HTML/CSS project without the use of Angular or React?

For my project, I am aiming to create a login and register page using TypeScript. Currently, my code is functioning well even without a database. However, I would like to implement Firebase for storing user credentials so that the login process becomes mor ...

Access PDF document in a fresh tab

How can I open a PDF file in a new tab using Angular 6? I have tried the following implementation: Rest controller: @RestController @RequestMapping("/downloads") public class DownloadsController { private static final String EXTERNAL_FILE_PATH = "/U ...

Execute a chain of consecutive HTTP requests and receive an Observable in response

I am currently working on two observable request functions that need to run sequentially in order for the desired outcome. Although it is functioning, I am facing an issue where the print function needs to be executed after the newOrder api call and return ...

Can a lightweight database be utilized in a Nativescript project focused on code sharing?

Currently, I am in the process of launching a new code sharing project using nativescript. My main goal is to create an offline app suitable for both tablets and desktops. I have successfully implemented code sharing following this guide: . Now, my focus ...

The return type in Typescript is populated with a generic type name that lacks meaningful

When utilizing ts-results-es, I encounter an issue. This library aids in wrapping errors within a class to provide insight into potential function errors. Here is a simplified class definition: interface BaseResult<T, E> {} class Err<E> imple ...

Tips for achieving asynchronous data retrieval using Angular Observable inside another Observable

What is my goal? I have several components with similar checks and data manipulation activities. I aim to centralize these operations in an observable. To do this, I created an observable called "getData" within my service... The unique aspect of "getData ...

A service worker of unknown origin is currently getting registered

Currently, I am using the service worker provided in create-react-app. After registering it in index.tsx with serviceWorker.register();, everything seems to be working fine. However, upon closer inspection in the dev tools' Application tab, I noticed ...

The TypeScript declarations for the scss module are malfunctioning

Just recently, I set up a React project using rollup. Below is the configuration file for my rollup setup: rollup.config.js import serve from "rollup-plugin-serve"; import livereload from "rollup-plugin-livereload"; import babel from &q ...