打字稿角度错误:无法读取未定义的属性“ toLowerCase”

时间:2019-04-27 11:15:42

标签: json angular typescript

我想用服务组件解析json本地文件,但是即使我不使用toLowerCase,我在尝试获取json时也会收到错误Cannot read property 'toLowerCase' of undefined

这是我获取数据的服务功能:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

import { Card } from './card';
import { MessageService } from './messages/message.service';
import {search} from "../assets/search.json"

@Injectable({
  providedIn: 'root'
})
export class CardService {
  private cardsUrl = 'api/cards';  // URL to web api

  constructor(
     private http: HttpClient,
     private messageService: MessageService) { }

  getCards(): Observable<Card[]>{
    const url =search;
    var datas =  this.http.get<Card[]>(url);


    console.log('data : '+datas);
    return datas;

  }
}

我正在尝试使用此函数获取类型为Card []的数组。 控制台日志显示data : [object Object]。 并且如果我打印console.log('data : '+datas[1]);,它会为undefined打印datas[1]。 我的卡片对象:

export class Set{
  code: string;
  name: string;
  type: string;
  block: string;
  image: string;
  rareNumber: number;
  uncommonNumber: number;
  commonNumber: number;
  landNumber: number;
  marketingNumber: number;
  releaseDate: number[];
}
export class Card {
  nameEnglish1: string;
  nameFrench1: string;
  nameEnglish2: string;
  nameFrench2: string;
  manaCost: string;
  cmc: number;
  colors: string[];
  colorIdentity: string[];
  type: string;

  //set here
  set: Set;

  textEnglish: string;
  textFrench: string;
  flavorEnglish: string;
  artist: string;
  number: number;
  power: string;
  toughness: string;
  loyalty: string;
  layout: string;
  multiverseidEnglish: number;
  multiverseidFrench: number;
  imageUrlEnglish: string;
  imageUrlFrench: string;
  rulings: string[];
  originalTextEnglish: string;
  originalType: string[];
  variations: string[];
  mtgid: string;

}

编辑:

我将这样的数据保存在一个组件中:

  getCards(): void{
    this.card_service.getCards()
      .subscribe(cards => this.cards = cards);
  }

用于显示数据的EDIT2 html代码:

<div class="card_container">
    <mc-search-bar></mc-search-bar>

      <div class="row no-gutters table-wrapper-scroll-y card_grid">
            <div *ngFor="let card of cards" class="col-sm-2">
                <img [src]="card.picture_url" class="rounded grid_space" [alt]="card.name"
                    data-toggle="popover-hover"  data-placement="top">
            </div>
      </div>
</div>

1 个答案:

答案 0 :(得分:3)

您应该像这样在订阅中移动数据

getCards(): Observable<Card[]>{
    const url =search;
    this.http.get<Card[]>(url).subscribe(data=>{
       console.log('data : '+data);
       return data;
   });
}

或这样使用

getCards(): Observable<Card[]>{
    const url =search;
    return  this.http.get<Card[]>(url)
}

在您的组件中使用

this.cardService.getCards().subscribe(data =>{
    this.datas = data;
})