简体   繁体   中英

Angular 2 getting json data from api to array

I need to fetch JSON data to the array, and with the press of a button to create a new list. Any solutions?

import { Component } from '@angular/core';
import { RandomService } from '../services/random.service';

@Component({
selector: 'pocetna',
template: `
<ul>
<li *ngFor="let joke of jokes">{{joke.value}}</li>
</ul>
<button (click)="getJoke()">more jokes</button>`,

providers: [RandomService]
})
export class PocetnaComponent  { 
jokes:Joke[] = [];

constructor(private jokesService: RandomService){}

ngOnInit() {
this.getJoke()
}

getJoke() {
this.jokesService.getRandomJokes()
.subscribe(joke => {
   this.jokes.unshift(joke)
})    
}
}
interface Joke{
id: number;
value: string;
}

This is how my service looks like, I think I'm missing something in it

import { HttpModule } from '@angular/http';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RandomService {
constructor(private http: Http){
console.log('working');
}
getRandomJokes(){
 return this.http.get('https://api.chucknorris.io/jokes/random')
.map(res => res.json()) 
.map(joke => <Joke>{id: joke.id, value: joke.value});
}

}

This code worked before restarting application but now this line of code says it can't find :

.map(joke => <Joke>{id: joke.id, value: joke.value});

I think you're trying to convert the json returned in the api to array loop through the json and convert it into array

 loadMore() {
        this.jokes = this.service.getRandomJokes()
            .subscribe(joke => { 
 const getdata = [];
 for(let key in data){
getdata.push(data[key]);
} 
this.jokes =getdata
});
    }

https://api.chucknorris.io/jokes/random it's response a object.

Make response with a array

[
    {
      "category": null,
      "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
      "id": "RPVWYzLySH277dwK-Se3PQ",
      "url": "http://api.chucknorris.io/jokes/RPVWYzLySH277dwK-Se3PQ",
      "value": "Chuck Norris is allowed to draw pictures of Mohammad"
    }
]

I guess that you've got problem with parsing data in the response.

You can try this:

 .map(res => res.json()) .subscribe( data => console.log(data), err => console.log(err), () => console.log('Random Quote Complete') ); 

OR:

 .map((res: Response) => { let data = (res.json() || {}).data; return data; }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM