1

I have this array:

productCarts: ProductModel[] = [];

And when I call this method in ngInit I have error Cannot read property 'length' of null:

addProductFromLocalStorage() {

            if (this.productCarts.length == 0) {
                this.productCarts  = this.fromLocalStorage;  
            } 
    }

Solution: My local storage return the null value and I hade exception.

3
  • 1
    It seems like this.fromLocalStorage is null Commented Nov 6, 2019 at 10:24
  • 1
    you may be assigning null to productsCarts somewhere. Commented Nov 6, 2019 at 10:25
  • 2
    give a bit more context. most likely you loose the this context when calling addProductFromLocalStorage(). Commented Nov 6, 2019 at 10:26

3 Answers 3

3

Try This :

addProductFromLocalStorage() {

            if (!this.productCarts || this.productCarts.length === 0) {
                this.productCarts  = this.fromLocalStorage;  
            } 
    }

!this.productCarts this will check null and undefined value

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. This is helpful.
2

Try using,

addProductFromLocalStorage() {

        if (this.productCarts === undefined || this.productCarts.length == 0) {
            this.productCarts  = this.fromLocalStorage;  
        } 
}

The is error Cannot read property 'length' of null is encountered as this.productCarts has not been defined yet. You can also use the second approach as declare productCarts:ProductModel[] in the global execution context and in ngInit method mention this.productCarts = []. Using this approach would also help.

1 Comment

Thanks a lot. This is helpful.
1

You can solve this issue with the latest Typescript 3.7 feature called optional chaining: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#optional-chaining

1 Comment

I hade a problem because my local storage returns the null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.