sander
sander

Reputation: 1654

Why won't the array update after subscribing to a service?

I'm trying to retrieve a list of movies from a Web Api server that runs on my localhost. The server does return data when I call it with Get request using HttpClient module, but I can't seem to be able to display the data.

MovieList Component

import { Component, OnInit } from '@angular/core';
import { MovieService } from '../services/movie.service';
import { IMovie } from '../Interfaces/IMovie';

@Component({
  selector: 'app-movielist',
  templateUrl: './movielist.component.html',
  styleUrls: ['./movielist.component.css'],
  providers: [MovieService]
})
export class MovielistComponent implements OnInit {
  private _movieService: MovieService;
  movies: IMovie[] = [];
  movie: IMovie;

  constructor(movieService: MovieService) {
    this._movieService = movieService;
  }

  ngOnInit(): void {
    this.getMovies();
  }
  getMovies(): void {
    this._movieService.getMovies().subscribe(movies => {
                                                        this.movies = movies;
                                                        return movies;
                                                        })
  }

}

MovieService Component

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IMovie } from '../Interfaces/IMovie';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class MovieService {
  private _movieUrl = 'http://localhost:50898/api/movie';
  private _http: HttpClient;

  constructor(http: HttpClient) {
    this._http = http;
  }

  getMovies(): Observable<IMovie[]> {
    return this._http.get<IMovie[]>(this._movieUrl);
  }

}

If I look at the Chrome Developer Tools Network Tab I can see that the server responds with this:

[{"MovieID":1,"Name":"shining","Details":"details","MeetingDate":null},{"MovieID":2,"Name":"one flew over cuckoo","Details":"details","MeetingDate":"2018-05-07T00:00:00"},{"MovieID":3,"Name":"up","Details":"animaation","MeetingDate":"2018-05-07T00:00:00"}]

MovieListComponent HTML.Template

<p>
  movielist works!
</p>

<div *ngIf="movies">
    <ul>
      <li *ngFor="let movie of movies">
        <span>{{movies.MovieID}}</span>
      </li>
    </ul>
</div>
<button>
</button>

IMovie Interface:

export interface IMovie {
  MovieID: number;
  Name: string;
  Details: string;
  MeetingDate: Date;
}

Here's the MSSQL database:

enter image description here

Upvotes: 0

Views: 50

Answers (1)

Fabio Ruggiero
Fabio Ruggiero

Reputation: 309

Care about typo.

<div *ngIf="movies">
    <ul>
      <li *ngFor="let movie of movies">
        <span>{{ movie.MovieID }}</span>
      </li>
    </ul>
</div>

In your MovieList Component you can get rid about that return statement:

getMovies(): void {
    this._movieService.getMovies()
        .subscribe(movies => {
            this.movies = movies;
        });
}

Upvotes: 1

Related Questions