'ERROR TypeError: Cannot read property 'extras' of null
this is my code and I am getting the error "ERROR TypeError: Cannot read property 'extras' of null "
ngOnInit() {
const navigation = this.router.getCurrentNavigation();
const state = navigation.extras.state as {
api: string;
trace_id: string;
token_id: string;
hotel_code: string;
result_index: string;
};
this.reqObj = {
api: state.api,
trace_id: state.trace_id,
token_id: state.token_id,
hotel_code: state.hotel_code,
result_index: state.result_index
};
}
Solution 1:[1]
You might need to invoke getCurrentNavigation() in the constructor. Also you could define an interface to avoid repeating the object type. Try the following
export interface Hotel {
api: string;
trace_id: string;
token_id: string;
hotel_code: string;
result_index: string;
}
@Component({
selector: 'my-details',
templateUrl: './details.component.html',
styleUrls: [ './details.component.css' ]
})
export class DetailsComponent implements OnInit {
reqObj: Hotel;
constructor(private router: Router) {
this.reqObj = this.router.getCurrentNavigation().navigation.extras.state as Hotel;
}
ngOnInit() {
}
}
Solution 2:[2]
Did you included the right Router at constructor? Like:
import { Router } from '@angular/router';
constructor(public router: Router)
{
const navigation = router.getCurrentNavigation();
}
Solution 3:[3]
In case state is used with [routerLink], it's ignored... (Angular - Issue with routerLink and state)
Solution 4:[4]
data: '';
constructor(public router: Router) {
let data = this.router.getCurrentNavigation().extras.state;
if(data)
this.data = data;
}
Check with if statement and your data will be available.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ruth |
| Solution 2 | Furiacs |
| Solution 3 | Mewster |
| Solution 4 | Olu Ayeni |
