angular - 错误类型错误:无法读取 Object.eval [as updateDirectives] 处未定义的属性“_id”
问题描述
我在数据绑定 _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)]
.
同时删除模板引用的分配#_id=“ngModel
。如果您甚至不需要使用它,请摆脱它。你会有这样的事情:
<div class="form-group">
<input type="hidden" name="_id" #_id [(ngModel)]="selectedIphoneId">
</div>
推荐阅读
- android-studio - Android studio 4.1 Emulator 扩展控件
- google-sheets - 谷歌表:如何自动将所有列添加到图形系列?
- jwt - 是否有可用于以编程方式验证 RS256 签名的 OAuth2 JWT 的在线服务?
- java - 水平设置工具提示文本
- php - 如何在select2中添加占位符
- sql - 循环 SQL SELECT 并从 R 中的数据框中更改参数
- c++ - 具有移动语义的函数的不同参数选项
- python - 在 setup.py 中设置入口点的工作目录
- sql - 如何在sql中获取唯一的行号
- c++ - 将构建的 libevent 链接为静态库时出现链接器错误,但在作为共享库链接时有效