【问题标题】:ERROR TypeError: Cannot read property 'map' of undefined angular 4错误类型错误:无法读取未定义角度 4 的属性“地图”
【发布时间】:2017-12-14 13:46:47
【问题描述】:

我想将chart.js 实现到我的angular 4 项目中。我将从json 文件中获取数据,然后将它们放入graphe。 当我编译我的代码时一切都很好,但是当我从 chrome 打开 t 时出现错误 无法读取 undifined 的属性“地图”。 有人可以帮我解决这个问题并说明为什么会出现这个错误。 这是我的代码 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
          }]
        }
      }
    });

  });
 }

【问题讨论】:

  • 如果您注销,res 中究竟是什么?
  • 看起来 res['list'] 未定义

标签: javascript angular typescript


【解决方案1】:

你需要检查 res['list'] 是否返回一个数组。 Javascript .map 方法不同于 'rxjs/add/operator/map';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 2018-02-17
    • 1970-01-01
    • 2019-11-16
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多