问题:错误TypeError:无法读取null角属性'push'

时间:2018-11-05 14:00:16

标签: angular typescript

我拥有财产category = <CategoryModel>{}; CategoryModel模型的模型是:

export class CategoryModel {
 public name: string;
 public description: string;
 public image: string;
 public products?: ProductModel[];


constructor(name: string, desciption: string, image: string = null, products: ProductModel[]) {
    this.name = name;
    this.description = desciption;
    this.image = image;
    this.products = products;
}
}

我想使用此代码categorycategoryList: CategoryModel[] = []; 存储到数组this.categoryList.push(this.category); 中,但是我遇到了错误ERROR TypeError: Cannot read property 'push' of null

这是我要在阵列中存储category并将其发送到服务器的post方法。

export class AdminComponent implements OnInit {


  category = <CategoryModel>{};


  //  category: CategoryModel[] = [];
  categoryList: CategoryModel[] = [];
  categoryProduct: ProductModel[];

  categoryForm: FormGroup;
  productForm: FormGroup;
  modalRef: BsModalRef;


  constructor(private http: HttpClient, private productsService: ProductsService, private dataStorageServiceService: DataStorageServiceService, private modalService: BsModalService, private adminService: AdminService) { }

  ngOnInit() {
    this.getCategory();
    this.initForm();
    console.log(this.categoryList);
  }

  getCategory() {
    this.dataStorageServiceService.getCategory()
      .subscribe(
        (cateogrys: CategoryModel[]) => {
          this.categoryList = cateogrys;
          console.log(this.categoryList)
        }
      );
  }


  storeCategoryList() {
    const nameCategory = this.categoryForm.value.name;
    const descriptionCategory = this.categoryForm.value.category;
    this.category.name = nameCategory;
    this.category.description = descriptionCategory;
    console.log(this.category);

    this.categoryList.push(this.category);
    this.dataStorageServiceService.storeCategoryList(this.categoryList).subscribe(

      (category: CategoryModel) => {
        category = this.category
        this.categoryList.push(category)
        console.log(this.categoryList)
      }

    )
}


  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }

  private initForm() {
    this.categoryForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'description': new FormControl(null, Validators.required),
      'image': new FormControl(null, Validators.required)
    })

    this.productForm = new FormGroup({
      'name': new FormControl(null, Validators.required),
      'description': new FormControl(null, Validators.required)

    })

  }




}

1 个答案:

答案 0 :(得分:0)

尝试从模态内部调用方法时,尝试将storeCategoryList()的签名更改为箭头函数,以将scope保留到外部类:

storeCategoryList = () => {
  // your existing code
}

希望有帮助!

相关问题