我正在写一个返回汽车数组的服务。我的服务方法不会返回成功或错误。文件夹assets
与`app folder。
这是我的服务方式:
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);
});
}
}
我称之为:
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)
});
}
}
这就是json
的样子:
{"data":[
{"vin":"a1653d4d","year":1998, "brand":"VW","color":"White"},
{"vin":"a1653d4w","year":1999, "brand":"VV","color":"White"}
]}
实体类:
export interface Car {
vin?;
year?;
brand?;
color?;
}
编辑: getCarsMedium()不会返回成功或错误。 控制台输出: CALL2 CALL1
答案 0 :(得分:1)
return this.http.get('assets/data/cars-medium.json')
.toPromise()
.then(res => res.json().data as Car[],
res => console.log(res));
显然,它不会打印任何东西,因为你从传递给then()的第二个回调打印响应,这是在拒绝承诺(不是)的情况下执行的。 / p>
改为:
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[]
});
答案 1 :(得分:0)
我找到了原因:我在项目中有jwt-authentication http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial][1] - 它阻止了我的请求