【发布时间】:2017-01-05 08:20:39
【问题描述】:
我在组件中使用 rjsx 从 http 获取数据(命名为 customer)。
然后我在客户中使用内部组件:
<customer>
<customer-form [customer]="customer"></customer-form>
</customer>
<!-- [customer]="customer" // here is data from http -->
在客户表单中我有:
@Input() customer:ICustomer;
complexForm : FormGroup;
constructor(fb: FormBuilder) {
this.complexForm = fb.group({
'name': [this.customer['name'], Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
});
}
但我明白了:
Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined
如果我理解正确:这是由于调用了构造函数,但尚未从 http 获取数据,因此 customer 为空。但是如何解决呢?
更新:我的 http 数据获取:
getCustomer(id) {
this.customerService.getCustomer(id)
.subscribe(
customer => this.customer = customer,
error => this.errorMessage = <any>error);
}
----
@Injectable()
export class CustomerService {
private customersUrl = 'api/customer';
constructor (private http: Http) {}
getCustomers (): Observable<ICustomer[]> {
return this.http.get(this.customersUrl)
.map(this.extractData)
.catch(this.handleError);
}
getCustomer (id): Observable<ICustomer> {
return this.http.get(this.customersUrl + '/' + id)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
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);
}
}
【问题讨论】:
-
只需添加一个默认值作为一个空字符串,它将显示给等待 http 结果的用户...
customer=defaultCustomer={name:''}
标签: javascript http angular rxjs