Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Angular 2 onclick add new item in array

I need to create new list item(value from api)on button press but don't know how to do it. Any help please? here is the code:

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

here is the service:

@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());
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just push an empty object

this.jokes.push({}); 

or if its going to be hooked up to a modal Create a class and push that

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

Or if you want to push from an 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());
}
}

Directive

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

I'm not sure if you load some random jokes and you want to load one more, or if you want to keep loading random jokes. If the later, you will want to take out the next function, and instead init your jokes array and keep pushing/applying to it. like so

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...