来自Angular的API的空响应

时间:2017-04-15 09:14:59

标签: c# json angular asp.net-core angular2-services

学习Angular 2并使用.Net Core构建应用程序
我有一个API,json响应传递给客户端。在我的Angular2服务中,使用Observable阅读回复并将其传递给我的component,然后传递给view
PostMan中测试,我的API正在响应预期的输出。我确定该服务有一些问题需要时间来解决。

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#class:

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

Angular 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

2 个答案:

答案 0 :(得分:1)

您在服务中的方法应该是这样的,

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

答案 1 :(得分:1)

export interface MovieProperties {    
id: string;
title: string;
}

改变这种情况对我有用。