Angular 6 is throwing an ERROR TypeError because it is unable to access the property 'length' of a null object

Recently delving into Angular 6, I've encountered an issue with two components: app.component.ts and products.component.ts, as well as a service file.

In the products component, I am receiving a JSON response in the ngOnChanges method. My goal is to retrieve the length of the JSON array and pass it to the app component.

For example, if the JSON array has a length of 10, I want to display "There are 10 products in this JSON array response," or something similar.

Although everything seems to be working fine for me, I keep getting a console error that I mentioned in my title. Despite trying different solutions, I haven't been able to resolve this issue.

Here's a snippet from app.component.ts:

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

And here's a segment from the service file:

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

Lastly, in products.component.ts:

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;
        });

}

If anyone could offer assistance in resolving this issue, I would greatly appreciate it.

Answer №1

Before accessing the data, it is crucial to check if it is empty. Debugging the data should be the first step to determine its status. Always make sure to validate the data before retrieving its length as doing otherwise can lead to potential risks.

this.CartdataService.get_Selected_Category_Of_Products(this.C_code,
      this.G_code, this.SG_code).subscribe(
        (data: any) => {
         if(data){ 
          this.totalProducts = data.length;
          this.CartdataService.productCountUnderCGS.next(this.totalProducts);
          this.productsList = data;}
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules library: SyntaxError: Cannot use import statement outside a module I'm positive that there is a configuration missing, b ...

A guide on how to retrieve an observer from localStorage or another observer in Angular2

Can anyone help me with my "loantype" service get() function: get() { return new Observable(observer => { let response; if ( localStorage.getItem('loantypes_are_valid') === '1' ) { response = JSON.parse(localStorage. ...

Understanding the tsconfig.json file in an Angular project

I encountered the following error in my tsconfig.ts file: 'No inputs were found in config file 'c:/Projects/Angular2//src/tsconfig.json'. Specified 'include' paths were '["src/**/*.ts"]' and 'exclude' paths ...

Updating Angular 2 template based on specific conditions of model values

I want to update a view only when the total votes reach a number that is a multiple of ten. I am incrementing a random element in an array called rows every 10 milliseconds, ultimately adding up to the total number of votes. Is there a simple way in angula ...

Typescript: Deciphering how to interpret a string with a mix of characters and numbers

Is there a way in TypeScript to add 40 to a variable of type string | number, and return a result as a string | number? My initial approach was to parse the variable to a number, then perform the addition, but how can I ensure that the variable is proper ...

Sending emails using Angular 4 and PHP

Having some trouble sending email from the PHP send function. It's sending an email, but not populating it with any data - it's coming through as null. This is my Send Service in Angular. The message here contains all the data from my form: ...

Unlock the full potential of your calendar with PrimeNG calendar setup

Seeking assistance with setting a value on a calendar control, I encountered an error on the following line and the value remains unset. this.data.dateIn = this.selecteddata.dateIn; <p-calendar [(ngModel)]="data.dateIn" [showIcon]="true" name="dateI ...

"Improve text visibility on your website with Google PageSpeed's 'Ensure text remains visible' feature, potentially saving you

Click here for the image reference showing the 0ms potential saving message I'm having trouble with a warning in Google PageSpeed and I've tried everything. This is the code I'm using to define the font-family: @font-face { font-family: ...

What steps should I take to convert the lazyload module in routes into a regular module?

Software Version: ng version: @angular/cli: 1.0.0-rc.1 node: 6.10.2 os: win32 x64 @angular/common: 4.1.1 @angular/compiler: 4.1.1 @angular/compiler-cli: 4.1.1 @angular/core: 4.1.1 @angular/forms: 4.1.1 @angular/http: 4.1.1 @angular/platform-browser: 4.1.1 ...

How can you transform a variable into an HTML element using Angular?

Currently, I am working on parsing a JSON file that contains information about various articles. The structure of the JSON file is as follows: { "articles": [ { "id": 1, "title": "<h1>How to install Atom</h1>" }, { ...

Combine all Angular Material Styles into a single CSS file rather than dynamically loading each style at runtime

I have encountered an issue in my Angular 8 Application where multiple style tags are dynamically generated at runtime for Angular Material. To address this, I am looking to add a CSP attribute to all my style tags after the build process is completed. To ...

Is there a way to obtain a unique response in TestCafe RequestMock?

With Testcafe, I have the capability to simulate the response of a request successfully. I am interested in setting up a caching system for all GET/Ajax requests. The current setup functions properly when the URL is already cached, but it fails to prov ...

How is it possible for a TypeScript function to return something when its return type is void?

I find the book Learning JavaScript to be confusing. It delivers conflicting information regarding the use of void as a return type in functions. const foo = (s: string): void => { return 1; // ERROR } At first, it states that if a function has a re ...

Accessing observable property in Angular 2 with TypeScript: A comprehensive guide

My observable is populated in the following manner: this._mySubscription = this._myService.fetchData(id) .subscribe( response => this._myData = response, ...

Step-by-step guide on setting up multiple tabs in Ionic to work with Firebase

I've been working on developing an offline-accessible application, but I'm facing some challenges. When I test the app without an internet connection, the cached data doesn't display properly. However, if I first open the app online and then ...

Explore Angular's ability to transform a nested observable object into a different object

My task involves mapping a field from a sub object in the response JSON to the parent object The response I receive looks like this: { "id": 1, "name": "file-1", "survey": { "identifier": 1, "displayedValue": survey-1 } } I am attempting ...

Choose the "toolbar-title" located within the shadow root of ion-title using CSS

Within Ionic, the ion-title component contains its content wrapped in an additional div inside the shadow-dom. This particular div is designated with the class .toolbar-title. How can I target this div using a SCSS selector to modify its overflow behavior? ...

Updating an image in Angular 6

I am currently working with Angular 6 and Firebase. I am looking to update an image on the server. Here is a snippet of my HTML: <div class="form-check"> <input type="file" (change)="onFileSelected($event)"> </div> This is the va ...

React Native error - Numeric literals cannot be followed by identifiers directly

I encountered an issue while utilizing a data file for mapping over in a React Native component. The error message displayed is as follows: The error states: "No identifiers allowed directly after numeric literal." File processed with loaders: "../. ...