Reputation: 333
I want to parse a json local file with a service component, but I get the error Cannot read property 'toLowerCase' of undefined
when I am trying to get the json, even though I don't use toLowerCase.
Here is my service function to get my data :
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;
}
}
I am trying to get an array of type Card[] with this function.
The console log shows data : [object Object]
.
And if I print console.log('data : '+datas[1]);
, it prints undefined
for datas[1]
.
My Card object :
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;
}
EDIT :
And I get my datas like this in a component :
getCards(): void{
this.card_service.getCards()
.subscribe(cards => this.cards = cards);
}
EDIT2 html code to display data :
<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>
Upvotes: 0
Views: 578
Reputation: 18973
You should move datas inside subscribe like this
getCards(): Observable<Card[]>{
const url =search;
this.http.get<Card[]>(url).subscribe(data=>{
console.log('data : '+data);
return data;
});
}
or use like this
getCards(): Observable<Card[]>{
const url =search;
return this.http.get<Card[]>(url)
}
And in your component use
this.cardService.getCards().subscribe(data =>{
this.datas = data;
})
Upvotes: 3