[英]Null response from API in Angular
学习 Angular 2 并使用 .Net Core 构建应用程序
我有一个 API, json
响应从中传递给客户端。 在我的Angular2
服务中,使用Observable
读取响应并将其传递给我的component
,然后view
.
在PostMan
测试,我的 API 正在响应预期的输出。 我确定该服务存在一些需要时间来解决的问题。
应用程序接口:
[HttpGet]
public List<MovieFields> Get()
{
path += @"\Data\MovieSource.json";
string jsonSource = System.IO.File.ReadAllText(path);
List<MovieFields> source = JsonConvert.DeserializeObject<List<MovieFields>>(jsonSource);
return source;
}
Json C# 类:
public class MovieFields
{
public string Id { get; set; }
public string Title { get; set; }
}
服务 :
export class MoviesService{
constructor(private http: Http) {
}
getMovies() {
return this.http.get('api/Movies')
.map(res => <Array<MovieProperties>>res.json());
}
}
成分 :
export class AllMoviesComponent implements OnInit {
private movieProp: Array<MovieProperties>;
ngOnInit() {
this.moviesService.getMovies()
.subscribe(ban => this.movieProp = ban);
}
角度 Json 接口:
export interface MovieProperties {
Id: string;
Title: string;
}
最后是我的 JSON:
[
{
"Id": "1",
"Title": "Olympus Has Fallen"
},
{
"Id": "2",
"Title": "Man of Steel"
} ]
答:编辑我的service
如下
getMovies(): Observable<MovieProperties[]> {
return this.http.get('api/Movies')
.map(this.extractData)
.catch(this.handleErrors);
}
private extractData(res: Response) {
let data = res.json();
return data;
}
Sajeetharan
你在服务里面的方法应该是这样的,
getMovies() : Observable<MovieProperties[]>{
return this._http.get('api/Movies')
.map((response: Response) => <MovieProperties[]>response.json())
.catch(this.handleError);
}
private handleError(error: Response){
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
export interface MovieProperties {
id: string;
title: string;
}
像这样改变案例对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.