我正在尝试从我的localhost上运行的Web Api服务器中检索电影列表。当我使用HttpClient模块使用Get请求调用它时服务器确实返回数据,但我似乎无法显示数据。
MovieList组件
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组件
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开发者工具网络标签,我可以看到服务器响应:
[{"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界面:
export interface IMovie {
MovieID: number;
Name: string;
Details: string;
MeetingDate: Date;
}
这是MSSQL数据库:
答案 0 :(得分:1)
关心拼写错误。
<div *ngIf="movies">
<ul>
<li *ngFor="let movie of movies">
<span>{{ movie.MovieID }}</span>
</li>
</ul>
</div>
在您的MovieList组件中,您可以删除该返回语句:
getMovies(): void {
this._movieService.getMovies()
.subscribe(movies => {
this.movies = movies;
});
}