Reputation: 89
When i make property as id!:string; or id:string=''; when i assign the value of params i get an error
(property) MoreParametersComponent.id: string ts(2322)Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-more-parameters',
templateUrl: './more-parameters.component.html',
styleUrls: ['./more-parameters.component.css']
})
export class MoreParametersComponent implements OnInit {
id!: string; // or id:string='';
id2:number=0;
constructor(private activatedRoute:ActivatedRoute) { }
ngOnInit(): void {
this.activatedRoute.paramMap.subscribe(params=>{
this.id=params.get('id'); // gives the above error here
this.id2=parseInt(params.get('id2'));//error
});
}
}
How do I get around this error?
My Rest of the Code:
app.component.html
<a routerLink=""> Home </a><br>
<a routerLink="one-parameter,'p01'"> One-Parameter </a><br>
<a routerLink="more-parameter,{id:'p02',id2:123}"> More-Parameter </a>
<br><br>
<router-outlet></router-outlet>
<br><br>
Route.config.ts
import { Routes } from '@angular/router'
import { HomeComponent } from './home/home.component';
import { MoreParametersComponent } from './more-parameters/more-parameters.component';
import { OneParamterComponent } from './one-paramter/one-paramter.component';
export const mainroute:Routes=[
{path:'',component:HomeComponent},
{path:'one-parameter',component:OneParamterComponent},
{path:'more-parameter',component:MoreParametersComponent}
];
Upvotes: 2
Views: 3519
Reputation: 13
You can try adding an exclamation '!' at the end to let the compiler know that the id will not be null.
this.id=params.get('id')!;
this.id2=parseInt(params.get('id2')!);
Upvotes: 0
Reputation: 1266
The return of ParamMap.get is string | null
which does not match your id
type.
You could cast the return of ParamMap.get to a string like params.get('id') as string
Or you could subscribe on params
instead which returns an object with property type any and access the the id param as an object key params.id
. See https://angular.io/api/router/Params
Upvotes: 3