0

As I am doing angular heroes tutorial from angular documentation. I am getting an error

Object is possibly 'null'.

getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
  .subscribe(hero => this.hero = hero);

}

in hero-detail.component.ts

link for the whole code hero-detail component

I have seen so many answers that to make it false in config.json. I need help with how to solve this, but not suppressing it.

Thanks in Advance.

2 Answers 2

2

you can do it in two steps

getHero(): void {
  const param=this.route.snapshot.paramMap.get('id');
  const id = param?+param:0;
  this.heroService.getHero(id)
    .subscribe(hero => this.hero = hero);
}
Sign up to request clarification or add additional context in comments.

1 Comment

so should we access another variable whenever we are using routing?
0

This is due to the stray plus sign combined with the fact the item this.route.snapshot.paramMap.get('id') might actually be null according to the Typescript type system so it's not a legitimate operand for +.

I recreated the same error with this code at this playground

const thing:string|null;

function getHero() : void {
const id = +thing;
}

Note the line that says...

const id = +thing;

enter image description here

If the use of + was intended as per Elisio's comment below, then you need to do something to guard the command, so that getHero not run at all when id is null, or that a reliable substitute value is provided for the id before running it. So long as there's a possibility it's null then

Typescript can't guarantee the operation will complete. This is good because it forces you to do the checks and add the safety.

4 Comments

in this case you can const id=thing?+thing:0
My interpretation of the error was that the plus sign had snuck in there and wasn't intended, but was creating a compiler error the OP couldn't interpret in a statement that was meant to just be a simple assignment like... const id = this.route.snapshot.paramMap.get('id')
I'm not pretty sure, but I think that the error is that you can not "operate" over a variable that can be null, but you can equal a variable to another that is (or can be) null. the "+" is a short way to convert in number a string that you know is a number: +"2"is 2 is like say Number("2")
Interesting, thanks. I've not used that but now I know.

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.