[英]Angular2 Service Returns Undefined
由於某種原因,我的服務無法正常工作。 我一直在潛伏兩天,試圖找到類似的問題,但是它們不適合我的問題。
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:{{cars.stylesCount | 異步}}
示例API響應: http : //pastebin.com/0LyZuPGW
錯誤輸出:
EXCEPTION: Error in ./EdmundsSearchResultComponent class
EdmundsSearchResultComponent - inline template:0:0 caused by:
Cannot read property 'stylesCount' of undefined
我想做的是從變量'styleurl'發出HTTP請求(我發現通過檢查chrome dev工具中的'Network'標簽成功完成了。)使用此API響應,我希望我的CarObject“消費” json響應,並且可用於我的組件/模板。
在組件中,您保留了car
屬性,但未初始化它,因此它保持undefined
。
當您的HTML呈現承諾尚未實現時,您的car
仍未undefined
但是您嘗試從中訪問屬性。
幾個解決方案:
預設 :
cars: CarObject = new CarObject(); // or <CarObject>{}
在模板中使用elvis運算符 :
{{ cars?.stylesCount }}
使用ngIf
:
<div *ngIf="cars">{{ cars.styleCount }}</div>
可能還有其他幾種方法可以處理這種情況。
有關使用async
管道的信息,請參閱底部的我的更新。 嘗試使用它的方式也可能會導致錯誤。
此外,我建議閱讀TypeScript類型以及有關angular和Typescript的一般最佳實踐,尤其是有關模型,接口等的用法。 另外,使用Observables代替Promises是個好主意。 您的代碼中存在一些問題,因此這僅是一個提示,但是我認為在這里對其進行詳細說明並不重要,也不是問題的根源。
希望我能幫上忙。
更新:
關於async
管道的用法:
異步管道訂閱Observable或Promise並返回其發出的最新值。
您在CarObjects
array
上使用它,但btw不應為數組。 查看異步管道的文檔以正確使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.