Reputation: 9808
I have angular app with a create function that adds a movie:
createMovie(movie: Movie): void {
this._dataService.createMovie<Movie>({'id': 20, 'name': 'Star Wars'})
.subscribe((data) => this.movie = data,
error => () => {
'something went wrong';
},
() => {
console.log(this.movies);
});
}
This calls the createMovie() function in the service:
public createMovie<T>(movie: Movie): Observable<T> {
console.log(movie);
return this.http.post<T>('/api/movies/', movie);
}
It's working fine. I can see that added object in the database and on a refresh on the page.
In my app.component.ts I have a movies: Movie[];
What is the correct way of adding the newly created movie to that array?
Upvotes: 2
Views: 64
Reputation: 424
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//Banana,Orange,Apple,Mango
fruits.push("Kiwi");
//Banana,Orange,Apple,Mango,Kiwi
Upvotes: 0
Reputation: 1692
you can use movies.push(movie)
. or use the spread operator "..." like [...movies, movie]
Upvotes: 0
Reputation: 4917
Simply change the createMovie()
method in your app.component to:
createMovie(movie: Movie): void {
this._dataService.createMovie<Movie>({'id': 20, 'name': 'Star Wars'})
.subscribe(
(data) => {
this.movie = data;
this.movies.push(this.movie); // <- adding the new movie to the movies array
},
(err) => {
// Error handling
},
() => {
console.log(this.movies);
});
};
Upvotes: 3