[英]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. 我需要将JSON数据提取到数组中,并按下按钮来创建新列表。 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 我认为您正在尝试将api中返回的json通过json转换为array循环并将其转换为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. https://api.chucknorris.io/jokes/random它是对对象的响应。
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; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.