首页 > 解决方案 > 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?我已经尝试在导致组件未正确加载的变量(即)之后设置问号。

这里的关键点是我的应用程序按预期工作但是我收到了这个非常奇怪的错误。

谁能告诉我这里有什么问题?先感谢您!

标签: angular

解决方案


@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>

我希望这能解决你的问题:)


推荐阅读