Issue
how to fix this problem.
in console have two type of error
1)Object is possibly 'undefined'.
=>error in code -->this.navigationExtras.state.value = item;
2)Property 'value' comes from an index signature, so it must be accessed with ['value'].
=>error in code -->this.navigationExtras.state.value = item;
list.component.ts file
import { Component, OnInit } from '@angular/core';
import { NavigationExtras,Router} from '@angular/router'
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
item:any;
navigationExtras: NavigationExtras = {
state: {
value :null
}
};
constructor(private router: Router) { }
ngOnInit(): void {
}
onGotoEdit(item:any):void{
this.navigationExtras.state.value = item; //error
this.router.navigate(['edit'])
}
onGotoSee(item:any):void{
this.router.navigate(['details'])
}
onGotoDelete(item:any):void{
alert('Deleted');
}
}
edit.components.ts
error in this file -->Type '{ [k: string]: any; } | undefined' is not assignable to type 'null'. Type 'undefined' is not assignable to type 'null'.
error in code --> this.value = navigation?.extras?.state
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router'
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.scss']
})
export class EditComponent implements OnInit {
value = null;
constructor(private router :Router) {
const navigation = this.router.getCurrentNavigation();
this.value = navigation?.extras?.state;
}
ngOnInit(): void {
}
}
Solution
Are you sure you don't know what type of item is being passed to onGotoEdit()? Would be nice to type check it. Let's add an if check, to make sure we have this obj where we are tying to assign item.
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
item:any;
navigationExtras: NavigationExtras = {
state: {
value : null
}
};
constructor() {
this.onGotoEdit('something');
console.log(this.navigationExtras)
}
onGotoEdit(item:any):void {
if (this.navigationExtras.state) {
this.navigationExtras.state['value'] = item;
}
}
}
Here is a working example: https://stackblitz.com/edit/angular-ivy-295kkz?file=src%2Fapp%2Fapp.component.ts
Answered By - Joosep.P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.