【发布时间】:2017-02-07 16:23:05
【问题描述】:
由于某种原因,我的服务无法正常工作。我已经潜伏了两天试图找到类似的问题,但它们不适合我的问题。
Service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { CarObject } from './make';
@Injectable()
export class EdmundsService {
private stylesurl = 'REDACTED';
constructor(private http: Http) { }
getCars(): Observable<CarObject[]> {
return this.http.get(this.stylesurl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
这些是我的“模型”:
class Style {
id: number;
name: string;
make: Make;
model: Model;
year: Year;
submodel: Submodel;
trim: string;
states: string[];
engine: Engine;
transmission: Transmission;
options: Options[];
colors: Color[];
drivenWheels: string;
numOfDoors: string;
squishVins: string[];
categories: Categories;
MPG: MPG;
manufacturerOptionCode: string;
}
export class CarObject {
styles: Style[];
stylesCount: number;
}
我的组件:
import { CarObject } from './make';
import { EdmundsService } from './edmunds-search-result.service';
@Component({REDACTED
providers: [EdmundsService] })
export class EdmundsSearchResultComponent implements OnInit {
cars: CarObject[];
errorMessage: string;
constructor(private _edmundsService: EdmundsService) { }
getCars(): void {
this._edmundsService.getCars()
.subscribe(
cars => this.cars = cars,
error => this.errorMessage = <any>error);
}
ngOnInit(): void {
this.getCars();
}
}
组件 HTML: {{汽车.stylesCount |异步 }}
示例 API 响应:http://pastebin.com/0LyZuPGW
错误输出:
EXCEPTION: Error in ./EdmundsSearchResultComponent class
EdmundsSearchResultComponent - inline template:0:0 caused by:
Cannot read property 'stylesCount' of undefined
- CarObject 旨在匹配 API 响应,因此可以删除数组括号 ( [] )
- 我不知道为什么尽管密切关注英雄之旅 HTTP/服务教程,但它不会在我的模板上显示对象数据。
我想要做的是从变量“styleurl”发出一个 HTTP 请求(我看到这是通过检查 chrome 开发工具中的“网络”选项卡成功发出的。)使用这个 API 响应,我希望我的 CarObject '消费 json 响应,并可供我的组件/模板使用。
【问题讨论】:
-
虽然问题不一样,但两个问题的答案都是一样的。检查我在上面问题中的答案。
-
@SabbirRahman 我看了你的回答,还是不明白该怎么做。请更明确。
-
您正在尝试访问
cars对象的stylesCount属性,该属性在模板首次尝试访问时未定义。要解决这个问题,您只需在声明时为汽车对象分配一个空对象。declare cars: any = {}。如果您不想使用any,则必须分配默认对象而不是 {}。 -
@SabbirRahman 我已将
cars: CarObject;替换为declare cars: any = {}并收到以下错误(15,3): declare modifier cannot appear on a class element.)
标签: javascript json angular typescript angular2-services