[Solved] Angular 2 onclick add new item in array


You have a few problems…

You have this interface:

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

what you are receiving is much more properties, so you’d need to pick the properties you want:

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})
}

Then you have problems in the subscribe, you should push the data to your jokes array and not do:

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

but:

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

notice above that I named this (joke => this.jokes.push(joke)) to make it clearer that you are actually just receiving one joke.

Also I would remove the request from the constructor, we have the OnInit hook for this. Also I would apply the request in a separate function, so that it’s easy to call when you want to retrieve new jokes and also therefore reuse the function, so something like this:

ngOnInit() {
  this.getJoke()
}

getJoke() {
  this.jokesService.getRandomJokes()
    .subscribe(joke => {
       this.jokes.push(joke)
    })    
}

So then in your template just call getJoke when you want to retrieve a new joke:

<ul>
  <li *ngFor="let joke of jokes">{{joke.value}}</li>
</ul>
<button (click)="getJoke()">more jokes</button>

Here’s a DEMO

0

solved Angular 2 onclick add new item in array