角度:TypeError:无法读取未定义的属性“映射”

时间:2019-06-03 10:16:11

标签: node.js angular mdbootstrap

我正在使用MEAN Stack来构建评分应用。我正在尝试通过服务代码将数据库中的项目列表获取到Angular组件中,但是我一直在获取core.js:14597 ERROR TypeError: Cannot read property 'map' of undefined

//scoring.service.js
import { Scoring } from './scoring.model';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';


@Injectable({providedIn: 'root'})
export class ScoringService {
    private scoring: Scoring[] = [];
    private updatedScores = new Subject<Scoring[]>();

    constructor(private http: HttpClient, private router: Router){}

    getScoring() {
        this.http.get<{message: string,   scores: any}>('http://localhost:3000/api/scoring')
            .pipe(map((scoringData) => {
                return scoringData.scores.map(score => {
                    status = score.IsActive ? 'checked' : 'unchecked';
                    return {
                        id: score._id,
                        Criteria: score.Criteria,
                        MaxPoints: score.MaxPoints,
                        IsActive: status, 
                        DateCreated: score.DateCreated,
                        DateModified: score.DateModified
                    };
                });
            }))
            .subscribe((transformedScores) => {
                this.scoring = transformedScores;
                this.updatedScores.next([...this.scoring]);
            });
    }
}

该代码应列出项目,并将booleantrue中的false字段分别映射到选中或未选中。但是什么都没有列出。我得到的错误是"Cannot read property 'map' of undefined.",并且我在另一个组件中使用了相同的代码集来列出项目而没有得到该错误。请在这里帮助我,我将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

pipe(map(scoringData))部分中放置一些断点,然后看看会得到什么。

抛出该异常是因为您实际上假设“ scoringData”返回的对象格式如下:

{"scores": [ << an array of something >> ]}

但是,如果scoringData为null,则您尝试将.map函数用于未定义的结果。

快速修复可以是:

.pipe(map((scoringData) => {
  return (scoringData && scoringData.scores || []).map(score => {
     status = score.IsActive ? 'checked' : 'unchecked';
     return {
         id: score._id,
         Criteria: score.Criteria,
         MaxPoints: score.MaxPoints,
         IsActive: status, 
         DateCreated: score.DateCreated,
         DateModified: score.DateModified
     };
   });
}))

更好的方法是在管道中使用地图之前先过滤结果。

这取决于您使用的RxJS库,但是通常您可以执行以下操作:

.pipe(filter(scoringData => !!scoringData && !!scoringData.scores && scoringData.scores.length), map((scoringData)

并且filter运算符的导入应与map运算符相同:

import { filter } from 'rxjs/operators';