2

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?

2
  • 2
    just simple javascript.. should be movies.push(movie) Commented Sep 19, 2017 at 17:02
  • upvote for @bgraham Commented Sep 19, 2017 at 17:09

3 Answers 3

3

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);
    });
};
Sign up to request clarification or add additional context in comments.

Comments

0

you can use movies.push(movie). or use the spread operator "..." like [...movies, movie]

Comments

0
var fruits = ["Banana", "Orange", "Apple", "Mango"];
//Banana,Orange,Apple,Mango

fruits.push("Kiwi");
//Banana,Orange,Apple,Mango,Kiwi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.