Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.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
Angular 错误类型错误:无法读取属性';长度';角6中的空值_Angular_Typescript - Fatal编程技术网

Angular 错误类型错误:无法读取属性';长度';角6中的空值

Angular 错误类型错误:无法读取属性';长度';角6中的空值,angular,typescript,Angular,Typescript,我是angular 6的新手,这里有两个组件app.component.ts、products.component.ts和service file 在使用ngOnChanges方法接收json响应的products组件中,我需要做的是,获取json数组长度并将其传递给应用程序组件 Ex:如果json数组长度是10,那么我将在这个json数组响应中显示10个产品 对我来说,它工作得很好。但我在标题中提到了控制台错误。我尝试了一些解决方案,但没有解决这个问题 app.component.ts th

我是angular 6的新手,这里有两个组件app.component.ts、products.component.ts和service file

在使用ngOnChanges方法接收json响应的products组件中,我需要做的是,获取json数组长度并将其传递给应用程序组件

Ex:如果json数组长度是10,那么我将在这个json数组响应中显示10个产品

对我来说,它工作得很好。但我在标题中提到了控制台错误。我尝试了一些解决方案,但没有解决这个问题

app.component.ts

 this.CartdataService.productCount.subscribe(
  (data :any) =>{
    this.size  = data;
  });
ngOnChanges(changes: SimpleChanges) {

    this.C_code = this.CartdataService.category_code;
    this.G_code = this.CartdataService.group_code;
    this.SG_code = this.CartdataService.subgroup_code;

    this.CartdataService.get_Selected_Category_Of_Products(this.C_code,
      this.G_code, this.SG_code).subscribe(
        (data : any) => {
          this.size = data.length;
          this.CartdataService.prooductCountUnderCGS.next(this.size);
          this.products = data;
        });

  }
服务

public prooductCountUnderCGS = new BehaviorSubject<number>(0);
  productCount = this.prooductCountUnderCGS.asObservable();

谁能帮我解决这个问题。

你需要检查是否有空数据。首先调试dat,查看它是否为空。然而,您需要检查数据才能查看。调用对象的长度而不检查其值是有风险的

 this.CartdataService.get_Selected_Category_Of_Products(this.C_code,
      this.G_code, this.SG_code).subscribe(
        (data : any) => {
         if(data){ 
          this.size = data.length;
          this.CartdataService.prooductCountUnderCGS.next(this.size);
          this.products = data;}

        });

在投票否决postHi Zhu之前给我解释一下,只是我有一个问题,而不是从product.component发送长度,你是尝试在app.component中通过this.size=data.length获取长度,还是通过插值检查data.length直接在html文件中计算长度,
console.log(data)是否偶然为空?不可能为空@eduPeeth@Zhu您可以通过日志记录或开发人员控制台调试器检查数据值吗。IMHO
data
肯定是空的,因此会出现错误。Bro页面加载后,json长度将为空,它将返回数据,只有用户更改页面中的某些值。因此,我应该如何防止应用程序出现此错误@Raminahmadi您需要在调用任何服务之前检查数据是否为空,否则,您将传递null,这是毫无意义的(如果我错了,请纠正我)。所以您只需要检查数据,就这么简单:)。更新了我的答案,顺便说一句