Tengo un componente de botón que toma un parámetro de id transmitido por su componente principal. En this.crudService.DeletePost(this.id).subscribe( data => console.log(data)) , ¿por qué recibo un error de
Argumento de tipo 'cadena | undefined' no se puede asignar a un parámetro de tipo 'string'.
[1] El tipo 'indefinido' no se puede asignar al tipo 'cadena'.
import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { CrudService } from 'src/app/service/crud.service'; @Component({ selector: 'app-kehbab-menu', templateUrl: './kehbab-menu.component.html', styleUrls: ['./kehbab-menu.component.css'] }) export class KehbabMenuComponent implements OnInit { @Input() id?: string; constructor(private router: Router, private crudService: CrudService) { } ngOnInit( ): void { } async removePost() { //delete -- this is where I get the error saying this.id is undefined but I can console log it and it shows the id. await this.crudService.DeletePost(this.id).subscribe( data => console.log(data)); //refresh home await this.router.navigateByUrl('/search', { skipLocationChange: true }).then(() => { this.router.navigate(['/home']); }); } }¿Por qué recibo un error de "El argumento de tipo 'cadena | indefinido' no se puede asignar al parámetro de tipo 'cadena'.
Simplemente se le advierte de un problema potencial en su código. ¿Ha definido @Input() id?: string; . Esto significa que id es una string o no está undefined . Luego pasa esta variable a this.crudService.DeletePost(this.id) que creo que acepta una string . Por lo tanto, está intentando asignar string | undefined a cadena.
Para resolver esto, tiene varias formas, una simple es simplemente verificar usando if
async removePost() { if (this.id) { //delete -- this is where I get the error saying this.id is undefined but I can console log it and it shows the id. await this.crudService.DeletePost(this.id).subscribe( data => console.log(data)); //refresh home await this.router.navigateByUrl('/search', { skipLocationChange: true }).then(() => { this.router.navigate(['/home']); }); } } También puede usar el operador no nulo this.crudService.DeletePost(this.id!) . Tenga en cuenta el !
Otra opción es encasillar this.crudService.DeletePost(this.id as string)
También puede simplemente definir su propiedad como una cadena con un valor predeterminado. Luego puede verificar si la propiedad es '0' en el servicio
@Input() id = '0';