Angular 2 onclick在数组中添加新项

时间:2017-05-25 16:12:46

标签: javascript angular

我需要在按下按钮时创建新的列表项(来自api的值),但不知道该怎么做。有什么帮助吗? 这是代码:

<ul>
<li *ngFor="let joke of jokes">{{joke.value}}</li>
</ul>
<button (click)="loadMore">more jokes</button>
`,
providers: [RandomService]

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

constructor(private jokesService: RandomService){
this.jokesService.getRandomJokes().subscribe(jokes => {this.jokes = 
[jokes]});
}

loadMore(){
this.jokes.push();
}

}
 interface Joke{
 id: number;
 value: string;
}

这是服务:

@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());
}
}

2 个答案:

答案 0 :(得分:1)

只需按空对象

this.jokes.push({}); 

或者它是否会被连接到模态 创建一个类并推送

Class IJoke {
 id: number;
 value: string;
 constructor(){
 }
}
this.jokes.push(new IJoke()); 

或者如果您想从API推送

@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());
}
getNextJoke(){
    return this.http.get('https://api.chucknorris.io/jokes/next')
    .map(res => res.json());
}
}

指令

loadMore(){
    this.jokesService.getNextJoke().subscribe(joke => {
        this.jokes.push(joke); 
    });
}

我不确定你是否加载了一些随机笑话,并且你想再加载一个,或者如果你想继续加载随机笑话。如果是后者,你会想要取出下一个函数,而是初始化你的jokes数组并继续推送/应用它。像这样

jokes: Joke[] = new Array();
constructor(private jokesService: RandomService){
this.jokesService.getRandomJokes().subscribe(jokes => {
    this.jokes.push(jokes)
}); 

答案 1 :(得分:1)

你有一些问题......

你有这个界面:

Users

您收到的内容是更多属性,因此您需要选择所需的属性:

interface Joke{
 id: number;
 value: string;
}

然后您在订阅中遇到问题,您应该将数据推送到getRandomJokes(){ return this.http.get('https://api.chucknorris.io/jokes/random') .map(res => res.json()); // pick the properties you want/need .map(joke => <Joke>{id: joke.id, value: joke.value}) } 数组而不是:

jokes

但:

.subscribe(jokes => {this.jokes = [jokes]})

上面注意到我将此.subscribe(joke => this.jokes.push(joke)} 命名为更清楚你实际上刚接到一个笑话。

另外我会从构造函数中删除请求,我们有OnInit钩子。此外,我会在一个单独的函数中应用请求,以便在您想要检索新的笑话并因此重用该函数时很容易调用,所以像这样:

(joke => this.jokes.push(joke))

然后在你的模板中,当你想要检索一个新的笑话时,只需调用ngOnInit() { this.getJoke() } getJoke() { this.jokesService.getRandomJokes() .subscribe(joke => { this.jokes.push(joke) }) }

getJoke

这是 DEMO