An error has occurred: Unable to access the 'map' property of undefined in Angular 4

I'm looking to integrate chart.js into my Angular 4 project. The plan is to retrieve data from a JSON file and display it on a graph. Everything seemed fine during compilation, but upon opening it in Chrome, I encountered an error stating "cannot read property 'map' of undefined". Can someone assist me in resolving this issue and explaining why it occurred? Below is my code in app.component.ts:

import {Component, OnInit} from '@angular/core';
import {trigger, state, style, transition, animate, keyframes} from 
'@angular/animations';
import { Chart } from 'chart.js';
import { WeatherService } from './weather.service';
import 'rxjs/add/operator/map';


@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [
trigger('myAnimation', [
state('small', style({transform: 'scale(1)', })),
state('large', style({transform: 'scale(2)', })),
  // transition('small <=> large', animate('500ms ease-in' , style 

 ({transform : ' translateY(40px)'}))),
  transition('small <=> large', animate('700ms ease-in' , keyframes([

    style ( { opacity: 0, transform : ' translateY(-75%)' , offset: 0})
    //style ( { opacity: 1, transform : ' translateY(400px)', offset : 
  0.5}),
  //  style ( { opacity: 1, transform : ' translateY(0)', offset : 1})


  ]))),
 ]),

 ]
 })
export class AppComponent implements OnInit {
 state: String = 'small';
 chart = [];
 temp_max = [ ];
 temp_min = [ ];

 constructor(private weather: WeatherService) {}
 ngOnInit() {
this.weather.dailyForecast()
  .subscribe(res => {
    let temp_min = res['list'];
    let temp_max = res['list'];
    let alldates = res['list'];
     temp_min.map(res => res.main.temp_max)
   temp_max.map(res => res.main.temp_min)
    alldates.map(res => res.dt)

    let weatherDates = []
    alldates.forEach((res) => {
      let jsdate = new Date(res * 1000)
      weatherDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric'}))
      })

    this.chart = new Chart('canvas', {
      type: 'line',
      data: {
        labels: weatherDates,
        datasets: [
          {
            data: temp_max,
            borderColor: '#3cba9f',
            fill: false
          },
          {
            data: temp_min,
            borderColor: '#ffcc00',
            fill: false
          },
        ]
      },
      options: {
        legend: {
          display: false
        },
        scales: {
          xAxes: [{
            display: true
          }],
          yAxes: [{
            display: true
          }]
        }
      }
    });

  });
 }

Answer №1

Always verify if the value of res['list'] is an actual array. Remember, the JavaScript .map function operates differently from 'rxjs/add/operator/map'.

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 most effective way to utilize an existing table in MySQL with a TypeORM entity?

While working with typeorm to connect to a mysql db, I encountered an issue where my table definition was overwriting an existing table in the database. Is there a way for me to use the entity module to fully inherit from an existing table without causin ...

Utilizing the button's id to display a partial view within Rails

I am working on a view that showcases a partial containing a list of events created by a user, each with an edit link alongside. My goal is to have a form partial appear below the event when the 'edit' link is clicked. To achieve this, I have su ...

What is the best way to showcase a single <ul> list in an infinite number of columns?

Utilizing Django on the backend, I aim to showcase the list below in an unlimited number of columns with overflow-x: auto. <ul class="list"> {% for i in skills %} <li>{{i}}</li> {% endfor %} </ul> Example Result: 1 7 ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

Tips for sending multiple variables to PHP using jQuery

Hello everyone, I could really use some assistance with a jQuery and AJAX issue I'm facing. I admit that I am not very well-versed in these technologies, so it's likely that I am missing something simple here. My problem lies in trying to pass mo ...

What exactly does Apple consider as a "user action"?

In the midst of my current web project, I am facing a challenge with initiating video playback after a swipe event. Despite utilizing the HTML5 video player and JavaScript to detect swipes, I have encountered difficulties in achieving this functionality. I ...

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

performing a request to Axios API with the inclusion of ${item} within the URL

I am having trouble with calling axios in Vuetify due to backticks and ${} within the URL. I believe I need to convert it into JSON format, but my attempts have been unsuccessful. Could you please provide an explanation? Here is the code snippet. Whenever ...

navigating through different pages on a react-native application

While building my app in react-native, I encountered some issues with setting up the navigation. I referred to the react-native documentation for guidance, specifically this navigation guide. The guide mentioned passing an object named "navigation" to your ...

When I click, I expect to retrieve the tr element, but instead, I am receiving the td element

When I have a table and click on a tr element, the function returns a td element instead. Can someone explain why this is happening? let func = function () { $("tr").on("click", (event) => { event.preventDefault(); event.stopPropaga ...

Using ajax to process form submissions

I'm encountering an issue with a form that I'm using to submit data via ajax. Firebug is throwing an error "ReferenceError: editUser is not defined". The form is located within a modal and I'm intending to use it for editing user information ...

When the onclick event is triggered, the return value will execute after the onclient

After my onclientclick event finishes, I am trying to run my onclick event. However, regardless of whether my checkbox is selected or not, the program keeps prompting me to "Please select at least one to delete." Can anyone help me figure out why this is h ...

The React Native Monorepo project encounters issues on the release build

Currently, I am experimenting with a Monorepo setup using the yarn workspaces method. Within this Monorepo, I have included a sample react-native project that is properly configured and runs smoothly in debug build mode. However, when I attempt to create a ...

How can recursion be implemented when the items are interdependent?

I am looking to create a function that can generate a list of individuals upon whom a specific person relies. The complexity here lies in the fact that these individuals may, in turn, rely on the original person. To illustrate: const people = { ' ...

The data points on the Google Maps heatmap are not visible

We are working on developing a server side application that will utilize the Google Maps API to create weighted heat maps for visualizing data. Check out the Google Maps API documentation for Heat Maps here Despite successfully displaying the map, my Jav ...

The directive subscription remains inactive even when the subject triggers the next function

Plunkr: https://plnkr.co/edit/KfPfVSbZm087uIPvFEkM?p=preview I have developed a service that serves as an API for a modal component. In addition, there is a directive available that can be used to apply a class to any element when the modal is open. Howev ...

Exploring the difference between loop and stream patterns in Azure Service Bus message receiving operations

I am currently setting up the Azure Service Bus messaging infrastructure for my team, and I am working on establishing best practices for developing Service Bus message receivers. We are in the process of creating a new service to consume the Service Bus m ...

Adding additional rows within an *ngFor loop can be achieved by dynamically updating the data source that the loop is iterating over. By manipulating the data structure

I am looking to add expand-collapse functionality to my tables using Angular 2. Specifically, I want the expanded portion to only show below the row that was clicked. I have attempted to achieve this with the code snippet below, but currently, the new row ...

What is the best way to have an image trail another in JavaScript coding for my game?

Hey, can someone help me create a zombie game where a zombie image moves towards a player image (zs.png) at a specific speed and decreases the player's health upon contact? This game is designed for the 3ds browser, so it must be coded in JavaScript ...

{ Battle of the Brackets } spawns the question: {

Exploring the world of child processes, I stumbled upon this comparison: const {spawn} = require('child_process'); I'm curious to know the distinction between the snippet above and the following: const spawn = require('child_process&ap ...