Learning Angular 2 and building an app with .Net Core
I've an API from which json
response is passed to Client Side. In my Angular2
service, used Observable
to read the response and pass it to my component
and then to view
.
Tested in PostMan
and my API is responding expected output. I'm sure the service has some issue which is taking time to resolve.
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; }
}
Service :
export class MoviesService{
constructor(private http: Http) {
}
getMovies() {
return this.http.get('api/Movies')
.map(res => <Array<MovieProperties>>res.json());
}
}
Component :
export class AllMoviesComponent implements OnInit {
private movieProp: Array<MovieProperties>;
ngOnInit() {
this.moviesService.getMovies()
.subscribe(ban => this.movieProp = ban);
}
Angular Json Interface :
export interface MovieProperties {
Id: string;
Title: string;
}
and finally my JSON:
[
{
"Id": "1",
"Title": "Olympus Has Fallen"
},
{
"Id": "2",
"Title": "Man of Steel"
} ]
Answer : edited my service
as below
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;
}
thanks Sajeetharan
Your method inside the service should be like this,
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');
}