![](/img/trans.png)
[英]ERROR TypeError: Cannot read property '1' of null at Object.eval [as updateDirectives]
[英]ERROR TypeError: Cannot read property '_id' of undefined at Object.eval [as updateDirectives]
数据绑定_id属性后,我收到此错误。 谁能帮我吗。
码:
<div class="form-group">
<input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="iphoneService.selectedIphone._id">
</div>
这是iphone.Service代码
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { Iphone } from "./iphone.model";
@Injectable()
export class IphoneService {
selectedIphone: Iphone;
iphones: Iphone[];
readonly baseUrl = "http://localhost:3000/iphone";
constructor(private http: HttpClient) {}
postIphone(iphon: Iphone) {
return this.http.post(this.baseUrl, iphon);
}
}
这里是iphon.model
export interface Iphone {
_id: string;
firstName: string;
lastName: string;
email: string;
colorPrefence: string;
contact: string;
country: string;
state: string;
city: string;
zipCode: string;
transactionId: string;
__v: string;
}
这是iphone.component.ts
@Component({
selector: "app-iphone",
templateUrl: "./iphone.component.html",
styleUrls: ["./iphone.component.css"],
providers: [IphoneService]
})
export class IphoneComponent implements OnInit, AfterViewChecked {
constructor(public iphoneService: IphoneService) {}
ngOnInit() {}
onSubmit(form: NgForm) {
this.iphoneService.postIphone(form.value).subscribe(res => {});
}
我认为我收到的错误是由于模型的绑定不正确造成的,但我无法弄清楚如何解决它。
您在设计工作流程时遇到一些问题。
首先,您尝试绑定到服务中存在的变量,而不是组件中存在的变量。 服务不应负责存储视图状态。 视图状态应由组件负责。 您将需要在组件上具有一个变量(例如selectedIphoneId
),然后可以在[(ngModel)]
使用该[(ngModel)]
。
还要删除模板引用#_id=“ngModel
。 如果您甚至不需要使用它,请摆脱它。 您将具有以下内容:
<div class="form-group">
<input type="hidden" name="_id" #_id [(ngModel)]="selectedIphoneId">
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.