bra*_*r19 5 javascript http rxjs angular
我从组件中的rjsx获取我的数据(让我们命名customer).
然后我在客户中使用内部组件:
<customer>
<customer-form [customer]="customer"></customer-form>
</customer>
<!-- [customer]="customer" // here is data from http -->
Run Code Online (Sandbox Code Playgroud)
在客户形式我有:
@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)])]
});
}
Run Code Online (Sandbox Code Playgroud)
但我得到:
Cannot read property 'name' of undefined
TypeError: Cannot read property 'name' of undefined
Run Code Online (Sandbox Code Playgroud)
如果我理解正确:这是因为构造函数被调用,但数据尚未从http获取,因此customer是空的.但是如何解决这个问题?
upd:我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
正如@Bhushan Gadekar所说,当您尚未初始化客户时,您正在访问该客户.
有多种方法可以正确处理:
@Input("customer")
set _customer(c:ICustomer){
this.customer=c;
this.complexForm.get("name").setValue(c.name,{onlySelf:true});
}
customer:ICustomer;
complexForm : FormGroup;
constructor(fb: FormBuilder) {
this.complexForm = fb.group({
'name': [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
});
}
Run Code Online (Sandbox Code Playgroud)
Observable在这里,客户的需要是Observable的ICustomer
@Input() customer:Observable<ICustomer>;
complexForm : FormGroup;
constructor(fb: FormBuilder) {
this.complexForm = fb.group({
'name': [this.customer['name'], Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
});
}
ngOnInit(){
this.customer.map(c=>this.complexForm.get("name").setValue(c.name,{onlySelf:true}))
.subscribe();
}
Run Code Online (Sandbox Code Playgroud)
@Input("customer")
set _customer(c:ICustomer){
this.customer.next(c);
}
customer=New Subject<ICustomer>();
complexForm : FormGroup;
constructor(fb: FormBuilder) {
this.complexForm = fb.group({
'name': [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(255)])]
});
}
ngOnInit(){
this.customer.map(c=>this.complexForm.get("name").setValue(c.name,{onlySelf:true}))
.subscribe();
}
Run Code Online (Sandbox Code Playgroud)
如果您不想逐个编写每个表单更新,并且如果表单的字段名称与您的对象相同,则可以遍历客户属性:
Object.keys(customer).forEach(k=>{
let control = this.complexForm.get(k);
if(control)
control.setValue(customer[k],{onlySelf:true});
});
Run Code Online (Sandbox Code Playgroud)
请注意,仅当表单的控件的命名方式与客户的属性相同时,此代码才有效.如果没有,您可能需要将客户属性名称的哈希映射到formControls名称.
Yous永远不应该从构造函数访问输入,因为它们尚未填充,所有输入应该在ngOnInit钩子之前填充(至少是同步的).看一下Lifecycle hooks文档
customer我可以看到您正在尝试在未填充对象时访问该对象。
这里的问题是 http 调用需要一些时间才能解决。因此,即使未定义,您的视图也会尝试访问客户对象。
尝试这个:
<customer *ngIf="customer">
<customer-form [customer]="customer"></customer-form>
</customer>
Run Code Online (Sandbox Code Playgroud)
尽管您获取财产的方式name也不好。最好的方法是创建一个客户模型并将您的财产用作className.propertyName
锄头这有帮助。