Why won't the array update after subscribing to a service?
我正在尝试从在我的本地主机上运行的Web Api服务器检索电影列表。当我使用HttpClient模块使用Get请求调用服务器时,服务器确实返回了数据,但是我似乎无法显示数据。
MovieList组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); } } |
如果我查看" Chrome开发者工具"的"网络"标签,则可以看到服务器以以下方式响应:
1 | [{"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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <p> movielist works! </p> <ul> <li *ngFor="let movie of movies"> <span>{{movies.MovieID}}</span> </li> </ul> <button> </button> |
IMovie接口:
1 2 3 4 5 6 | export interface IMovie { MovieID: number; Name: string; Details: string; MeetingDate: Date; } |
这是MSSQL数据库:
注意拼写错误。
1 2 3 4 5 6 7 8 9 | <ul> <li *ngFor="let movie of movies"> <span>{{ movie.MovieID }}</span> </li> </ul> |
在MovieList组件中,您可以摆脱该return语句:
1 2 3 4 5 6 | getMovies(): void { this._movieService.getMovies() .subscribe(movies => { this.movies = movies; }); } |