Reputation: 364
I am writing a service that returns array of cars. My service method dont return sucess or error. The folder assets
is in the same directory as `app folder.
This is my service method:
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Car} from '../../../domain/car';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class CarService {
constructor(private http: Http) {
}
getCarsMedium(): Promise<Car[]> {
console.log("call1");
return this.http.get('assets/data/cars-medium.json')
.toPromise()
.then(res => {
console.log("sucess1" + res);
console.log("sucess2" + res.json());
return res.json().data as Car[]
})
.catch(error => {
console.log("error");
console.error(error);
});
}
}
I call it as:
import {Component, OnInit} from '@angular/core';
import {Car} from "../../../domain/car";
import {CarService} from "./car.service";
@Component({
moduleId: module.id,
templateUrl: './car.component.html',
styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
cars: Car[];
constructor(private carService: CarService) {
}
ngOnInit() {
console.log("call2");
this.carService.getCarsMedium().then(function (cars) {
cars => this.cars = cars;
console.log(cars)
});
}
}
This is how my json
looks like:
{"data":[
{"vin":"a1653d4d","year":1998, "brand":"VW","color":"White"},
{"vin":"a1653d4w","year":1999, "brand":"VV","color":"White"}
]}
Entity class:
export interface Car {
vin?;
year?;
brand?;
color?;
}
EDIT: getCarsMedium() dont return sucess or error. console output: call2 call1
Upvotes: 0
Views: 297
Reputation: 364
I found the reason: I have jwt-authentication in project http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial][1] - it blocked my request
Upvotes: 0
Reputation: 691635
return this.http.get('assets/data/cars-medium.json')
.toPromise()
.then(res => res.json().data as Car[],
res => console.log(res));
Obviously, that won't print anything, since you're printing the response from a second callback passed to then(), which is executed in case the promise is rejected (which it is not).
Do that instead:
return this.http.get('assets/data/cars-medium.json')
.toPromise()
.then(res => {
console.log(res);
console.log(res.json());
return res.json().data as Car[]
});
Upvotes: 1