angular - Angular:无法读取未定义的属性“_id”
问题描述
任何人都可以建议为什么我在应用程序工作时在 Angular 7 中遇到错误
ERROR TypeError: Cannot read property '_id' of undefined
它确实指向组件:
<app-positions-form
*ngIf="!isNew"
[categoryId]="category._id">
</app-positions-form>
但在此之前我有:
<div>
{{category._id}}
</div>
正确显示值。
在我的组件中,我有:
export class CategoriesFormComponent implements OnInit {
@ViewChild('input') inputRef: ElementRef;
form: FormGroup;
image: File;
imagePreview;
isNew = true;
category: Category;
constructor(private route: ActivatedRoute,
private categoriesService: CategoriesService,
private router: Router) { }
ngOnInit() {
this.form = new FormGroup({
name: new FormControl(null, Validators.required)
});
this.form.disable();
this.route.params.pipe(
switchMap(
(params: Params) => {
if(params['id']) {
this.isNew = false;
return this.categoriesService.getById(params['id'])
}
// of returns Observable from anything
return of(null)
}
)
).subscribe(
category => {
if(category) {
this.category = category;
this.form.patchValue({
name: category.name
});
this.imagePreview = category.imageSrc;
MaterialService.updateTextInputs()
}
this.form.enable();
},
error => MaterialService.toast(error.error.message)
)
}
...
category?
我已经尝试在导致组件未正确加载的变量(即)之后设置问号。
这里的关键点是我的应用程序按预期工作但是我收到了这个非常奇怪的错误。
谁能告诉我这里有什么问题?先感谢您!
解决方案
@Aleksandr Popov在您获取类别对象时设置isNew
为。false
目前您在获取类别对象之前设置它。这就是你得到错误的原因。
this.route.params.pipe(
switchMap(
(params: Params) => {
if(params['id']) {
//this.isNew = false; <-- remove this line here
return this.categoriesService.getById(params['id'])
}
// of returns Observable from anything
return of(null)
}
)
).subscribe(
category => {
if(category) {
this.category = category;
this.isNew = false; <- set to false here
this.form.patchValue({
name: category.name
});
this.imagePreview = category.imageSrc;
MaterialService.updateTextInputs()
}
this.form.enable();
},
error => MaterialService.toast(error.error.message)
)
}
在您的子组件中设置一个问号
<div>
{{category?._id}}
</div>
我希望这能解决你的问题:)
推荐阅读
- javascript - Lottie 动画加载时如何淡入淡出?
- swift - 离线时如何在写入 Firebase 数据库之前检查服务器?
- sql - Sql join 与两个表最大和计数
- c++ - C++ Hello world 在 Visual Studio 2019 中不断给我错误
- javascript - React-Client-Session TypeError: undefined is not an object (evalating '_reactClientSession.default.setStoreType')
- facebook-graph-api - 如何确定为什么 facebook 页面 URL 不会返回 facebook id?
- php - 虚拟主机将我引导至 Xampp 仪表板
- php - 尝试在 Ajax 调用期间显示 Spinner 图像,但除非我处于调试模式,否则它将无法工作
- python - 将目标组添加到应用程序侦听器 (AWS CDK PYTHON)
- bash - shell 脚本中 GraphQL 查询中的特殊字符