Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在angular4 typescript中进行类初始化的更好方法_Angular_Typescript_Angular5_Angular6_Typescript2.0 - Fatal编程技术网

在angular4 typescript中进行类初始化的更好方法

在angular4 typescript中进行类初始化的更好方法,angular,typescript,angular5,angular6,typescript2.0,Angular,Typescript,Angular5,Angular6,Typescript2.0,在angular4中,在外部类内部初始化内部类的更好方法 这里有一个外部类名ProductsModel,它包含ProductsListModel。 我必须将ProductId字符串数组发送到服务器端请求。在外部类中初始化内部类时,下面的代码工作正常 不初始化时: export class ProductsModel{ productList : ProductListModel; } 执行此操作时,我收到以下错误消息: 无法将属性ProductId设置为

在angular4中,在外部类内部初始化内部类的更好方法

这里有一个外部类名ProductsModel,它包含ProductsListModel。 我必须将ProductId字符串数组发送到服务器端请求。在外部类中初始化内部类时,下面的代码工作正常

不初始化时:

  export  class ProductsModel{
        productList : ProductListModel;

        }
执行此操作时,我收到以下错误消息:

无法将属性ProductId设置为未定义

因此,我在下面像这样初始化,这是预期的工作,有没有更好的方式来初始化

Outer Class:

export  class ProductsModel{
productList = new ProductListModel();

}


export class ProductListModel{
ProductId:string[];

}

-- app. component.ts

export class AppComponent {

// initialsize  outer class here:

products = new ProductsModel();

in this subscribe:


DetailsByProductID(){


this.products.productList.ProductId = ['8901','8902'];
//pass the model object here 

this.ProductService.fetchByPID(this.products).subscribe(resposne=>console.log(response)});


}
}

您应该只在组件中进行初始化,保持类的属性不变

您收到错误“无法将
产品ID的属性设置为未定义”。因为产品为空

您可以像在类中一样在组件中进行初始化

products = new ProductsModel();

this.products.productList = new ProductListModel();

this.products.productList.ProductId = ['8901','8902'];

@Sajeetran好的,谢谢,还有其他标准化的方法来初始化内部组件吗?你所说的标准化方法是什么意思?如果你真的想要有默认值,你可以在类本身中定义。好的,当代码显示时,我得到了一条评论,比如不要在组件加载中初始化类,因此我问了这个问题。这取决于你试图做什么,正如我说的,如果你需要默认值,你应该在“不要在组件加载中初始化类“注释通常意味着将初始化代码从组件的构造函数移动到组件
ngOnInit
方法。但是,如果没有看到更多的代码,就很难判断它们在本文中的意思。在代码中键入:
resposne
而不是
response