0

I get the error:

EXCEPTION: value.indexOf is not a function

whenever I try to use a javascript function. Here is the code:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'id'
})
export class IdPipe {
    transform(value: string): string {
        let start = value.indexOf('"id": "')
        let id = value.substring(start + 7, start + 7 + 36);

        return id;
    }
}

What do I need to do to make this work? I see similar examples in other people's code, so I think this should work.

2
  • 1
    Can you check the type at the start of the function? console.log(typeof value); Commented Feb 1, 2017 at 14:36
  • The error means that the value of value is something that does not have an indexOf property. You can console.log(typeof value) before that to see what's going on. Commented Feb 1, 2017 at 14:39

2 Answers 2

2

you should insert condition in the begining of the transform function

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'id'
})
export class IdPipe {
    transform(value: string): string {
        if(value !== null && value !== undefined){
          let start = value.indexOf('"id": "')
          let id = value.substring(start + 7, start + 7 + 36);

          return id;
        }    
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your pipe will be executed multiple times. Some of these times, like when your component hasn't fully initialized yet, "value" will be null or possibly undefined, and then it will not have the indexOf method. That's why you're getting this error.

Add a safety check:

transform(value: string): string {
    if (!value) return value;

    let start = value.indexOf('"id": "')
    let id = value.substring(start + 7, start + 7 + 36);

    return id;
}

(I generally find it preferable to return early, but Yoav Schniederman's answer is perfectly valid as well.)

Comments

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.