有人可以建议为什么我在应用程序工作时出现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?
)之后设置问号,导致变量未正确加载。
关键要点是我的应用程序可以按预期运行,但是我遇到的错误非常奇怪。
有人可以告诉我这里有什么问题吗?谢谢你!
答案 0 :(得分:1)
@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>
我希望这能解决您的问题:)