Mat
Mat

Reputation: 711

ERROR TypeError: Cannot read property 'map' of undefined angular 4

I want to implements chart.js into my angular 4 project.I will get data from json file then i will put them into a graphe. When i compile my code all was good but when i opened t from chrome i got an error can not read proprerty 'map' of undifined . can someone help me to fix that and said why this error. this my code 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
          }]
        }
      }
    });

  });
 }

Upvotes: 1

Views: 2136

Answers (1)

Samuel Shyu
Samuel Shyu

Reputation: 151

You need to check whether res['list'] returns an array. Javascript .map method is different than 'rxjs/add/operator/map';

Upvotes: 1

Related Questions