What could be preventing the array from updating after subscribing to the service?

Attempting to fetch a list of movies from a Web API server on my localhost. The server does provide data when called with a Get request using the HttpClient module, but struggling to display it.

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

}

When checking Chrome Developer Tools Network Tab, the server responds with:

[{"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;
}

MSSQL database visual:

https://i.stack.imgur.com/ql8x8.png

Answer №1

Make sure to pay attention to typos.

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

In the MovieList Component, you can remove the return statement like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Universal: Execution of ngAfterViewInit occurring on the server side rather than the client side

While working on my server-rendered Angular application with Angular 17, I ran into a curious issue revolving around the ngAfterViewInit lifecycle hook. The situation arises when I call an init function within ngAfterViewInit, which relies on an API reques ...

Error message indicating a problem with global typings in Angular 2 when using Webpack is displayed

My project is utilizing angular 2 with webpack and during the setup process, I encountered Duplicate identifier errors when running the webpack watcher: ERROR in [default] /angular/typings/globals/node/index.d.ts:370:8 Duplicate identifier 'unescape& ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

Crafting a personalized arrow for sorting headers in Angular Material

Currently working on an Angular 5 project and I'm looking to implement a custom sort icon in the header. The goal is to achieve a similar effect to this example, without using the default arrow. I attempted to modify the CSS styles, but it wasn' ...

Angular proxy - Syntax error found in proxy configuration file: proxy.conf.json

My Angular 6 setup is configured to make HttpRequests, but I encountered a problem that requires me to run them through a proxy. To address this issue, I created a proxy.conf.json file next to my package.json: { "/loans/": { "target" : "https://api. ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...

Creating a service in AngularJS 1.8 with ES6 modules that acts as a bridge to a class based API interface

As I continue to enhance a codebase that originally consisted of a mix of different versions of AngularJs and some unstructured code utilizing various versions of a software API, I encounter an interesting quirk. It appears that this API is accessible thro ...

What is the best way to convert a `readonly string[]` to a regular `string[]`?

My data setup is as follows (I am not declaring it as an enum because it is used in both TypeScript server code and non-TypeScript client code): import { enumType } from 'nexus'; export const TYPE_ENUM = Object.freeze({ H: 'H', S: ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Issue "unable to use property "useEffect", dispatcher is undefined" arises exclusively when working with a local npm package

I am currently in the process of creating my very own private npm package to streamline some components and functions that I frequently use across various React TypeScript projects. However, when I try to install the package locally using its local path, ...

Issue deploying Angular 2 and Rails 5 on Heroku: npm command not found in bash

After successfully deploying an Angular2 on Rails5 app to Heroku and setting up the PG database, I encountered a stack trace in the Heroku app log indicating that the npm command was not found. This error has been perplexing as I try to troubleshoot the is ...

Optimal Approach for Redirecting Authorization

I'm currently working on setting up an authorization feature for my Angular application. Here is the detailed process I am following: First, I generate a state and code in the front end. Upon clicking the login button, the application redirects to /a ...

The android() method could not be located on the root project 'xyz' of type org.gradle.api.Project when passing [before_plugins_] as arguments

Encountering an issue while attempting to run the Nativescript Android application on my device. The error message states: Could not find method android() for arguments [before_plugins_d5qrcua3za3scd760qug60fz6$_run_closure1@5754ca71] on root project &apos ...

The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this: <!DOCTYPE html> <html> <head> <title></title> <style> button.accordion { background-color: #777; color: white; cursor: pointer; p ...

The specified type 'IterableIterator<number>' does not belong to either an array type or a string type

Encountering an error while attempting to generate a dynamic range of numbers. Error: Type 'IterableIterator<number>' is not recognized as an array or string type. Use the compiler option '--downlevelIteration' to enable iteratio ...

Error: Module not found - Unable to locate 'dropzone'

Since migrating from Angular 4.4 to Angular 8.0, I encountered the following issue: ERROR in ./src/attributes/import/import.component.ts Module not found: Error: Can't resolve 'dropzone' in 'C:....\src\attributes\imp ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

Angular 2 dropdown list that allows users to add a personalized value in the HTML code

Here is the scenario I am dealing with We are displaying a fixed dropdown list to the user For example, a dropdown list has 4 options such as apple, orange, grape, pineapple and 'create your own' If the user is not satisfied with the provided ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...