【发布时间】:2017-05-26 09:07:19
【问题描述】:
我需要将 JSON 数据提取到数组中,然后按一个按钮来创建一个新列表。有什么解决办法吗?
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;
}
这就是我的服务的样子, 我想我错过了一些东西
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});
}
}
此代码在重新启动应用程序之前工作,但现在这行代码说它找不到:
.map(joke => <Joke>{id: joke.id, value: joke.value});
【问题讨论】:
-
您的解决方案有效吗?你的问题似乎不太清楚。
-
它不工作,它没有获取任何数据
-
创建一个新列表是什么意思?
-
按下按钮将 API 推送到数组中并将其显示为新的
标签: javascript angular