Retrieve Information in a List

I am currently facing an issue while trying to retrieve data from an array. Below is an example of the image array that I am working with. I am specifically looking to get the weather icon data, but unfortunately I encountered this error message:

core.js:15724 ERROR TypeError: Cannot read property '0' of undefined

https://i.sstatic.net/i4dNK.png

Here is the code snippet:

weatherDaily(){
    this.commonService.getWeatherInfoDaily()
    .subscribe(
      (res) => {
        this.daily = res['list'];
        this.icon = res['list']['weather'][0]['icon'];
        console.log(this.icon);


      }
    )
  }

Answer №1

Suppose the code is:

this.icon = res['list'][0]['weather'][0]['icon'];

It's recommended to utilize interfaces when retrieving data from an API. This approach provides you with code suggestion features and simplifies the process of restructuring code if the API undergoes any modifications:

export interface WeatherListResponse {
  dt: number;
  // ... etc
}

export interface WeatherResponse {
  cod: string;
  message: number;
  cnt: number;
  list: WeatherListResponse[];
}

You can then specify generic typings on the HttpClient method to indicate to the compiler the expected response type, triggering an error if incorrect properties are accessed:

getWeatherInfoDaily(): Observable<WeatherResponse> {
  return this.http.get<WeatherResponse>(...);
}

weatherDaily() {
  this.commonService.getWeatherInfoDaily().subscribe((res) => {
    this.daily = res.list;
    // this.icon = res.list.weather[0].icon; <-- TypeScript error
    this.icon = res.list[0].weather[0].icon;

    // With the latest typescript version, you can use optional chaining:
    this.icon = res.list[0]?.weather[0]?.icon;

    console.log(this.icon);
  })
}

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

The component I created is not visible on the index page

I am new to Angular and I am trying to create a simple component, but I am facing an issue where my component is not showing up on the index page. Can someone please help me with this? Here is my component named "List.Component.ts": import { Component } ...

Retrieve the response status using a promise

There is a promise in my code that sometimes results in an error response (either 400 or 403, depending on the user). I am trying to handle this situation by catching the response and implementing a conditional logic to execute different functions based on ...

Injecting universal data into ValidationErrors in Angular

Trying to bind a value into ValidationErrors. Having this method: isUniqueEmail(control: FormControl): ValidationErrors { if (control.value != null) { console.log(control.value) if(control.value == this.foundEmail){ console ...

How to make Angular resolver and component share an injected service?

In my products list component, I have a table displaying various products. Since there is a considerable amount of data, I implemented a resolver to prevent the user from being directed to the page until all the data is loaded. The resolver currently utili ...

Trigger a post request by clicking the button to generate an excel report for download

I am attempting to download an excel file by making a POST call upon clicking a button in AngularJS. The Java controller I am working with returns void. This is the service code used to write to the excel file: response.setContentType("application/ms-exc ...

Nest may struggle with resolving dependencies at times, but rest assured they are indeed present

I've encountered a strange issue. Nest is flagging a missing dependency in a service, but only when that service is Injected by multiple other services. cleaning.module.ts @Module({ imports: [ //Just a few repos ], providers: [ ServicesService, ...

Encountered an issue while configuring the Apollo server - The type '() => void' cannot be assigned to type '() => DataSources<object>'

I need help with a TypeScript-related issue. I am struggling to implement the expected return type for the function dataSources in this scenario. Here is the code snippet: const dataSources = () => { quizzessApi: new QuizzessDataSource(); } const ...

After installing TypeScript community stubs, WebStorm is unable to locate the module

Recently, I tried to incorporate the ramda library into my project and went ahead to install its TypeScript community stubs in WebStorm. https://i.stack.imgur.com/fCFG8.png Despite my efforts, I encountered an error that stated — Cannot find module &a ...

Display Material UI icons as markers within Highcharts

Does anyone know how to use Material UI icons as markers in rendering? I have been searching for documentation but can't seem to find a clear explanation. Any guidance would be greatly appreciated! ...

Changing the default font size has no effect on ChartJS

I'm trying to customize the font size for a chart by changing the default value from 40px to 14px. However, when I set Chart.defaults.global.defaultFontSize to 14, the changes don't seem to take effect. Below is the code snippet for reference. An ...

Establishing a connection pathway for communication among components in Angular

I am faced with a situation where I have two components, CompA and CompA5, that are 3 or 4 levels apart. I need to establish a means of communication between these components. For instance, I want component CompA to send an event to CompA5, receive some d ...

Ways to trigger a function in Angular every 10 seconds

What is the method to utilize Observable function for fetching data from server every 10 seconds? Custom App service fetchDevices (): Observable<Device[]> { return this.http.get(this.deviceUrl) .map(this.extractData) .catch(this ...

You can't observe the behavior of simulated functions in a class with a manually created mock

Kindly note that I have set up a comprehensive Github repository where you can download and explore the content yourself here I am currently working on mocking a non-default exported class within a module using a manual mock placed in the folder __mocks__ ...

How can I decrypt a JWT token using Angular?

One of my current tasks involves decoding a jwt token that is provided by the API during the login process. Can anyone provide guidance on how to decode a jwt token in an Angular application? ...

An issue has occurred: TypeError - the data is not a function

I am attempting to pass the alpha2code variable through another component so that when a row in my table is clicked, it should display data specific to the alpha2code. This is the function that is triggered when a specific row in the table is clicked: on ...

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...

Tips for utilizing chodorowicz / ts-debounce effectively

Looking to utilize the debounce function provided by the ts-debounce package (available at here) in my typescript project. However, struggling to find a concrete example of its usage in typescript. Would greatly appreciate any help or guidance on this ma ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

What is the best way to extract a variable value from the subscribe method and make it available for use in an Angular 10 service method's return statement using TypeScript?

getProductbyFilter(filter: filterDataModel): Observable<any> { this.stringtoArrayService.convertStringtoArray(some string input).subscribe(productUserResponse => { if (productUserResponse) { this.userProfileProduct = productUserResponse; ...