简体   繁体   中英

error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'number'

I got this error while compiling and running this code with my angular application

error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'number'. Type 'null' is not assignable to type 'number'.

on this line: const id = this.activateRoute.snapshot.paramMap?.get('id');

full code:

 constructor(private shopService: ShopService, private activateRoute: ActivatedRoute) { } loadProduct(){ // tslint:disable-next-line: no-non-null-assertion const id = this.activateRoute.snapshot.paramMap?.get('id'); this.shopService.getProduct(id).subscribe(product => { this.product = product; }, error => { console.log(error); }); }

after adding any component I got the page: cannot GET /

I think I was close, and found the solution from related. I changed the line:

const id = this.activateRoute.snapshot.paramMap?.get('id');

just to be:

const id = +this.activateRoute.snapshot.paramMap.get('id')!;

and the error disappeared. Thanks for all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM