簡體   English   中英

角度:無法讀取未定義的屬性“ _id”

[英]Angular: cannot read property '_id' of undefined

任何人都可以提出建議,為什么在應用程序運行時我在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波波夫設置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>

我希望這能解決您的問題:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM