Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
Actualmente aprendiendo angular. ¿No puede usar la entrada como argumento porque tiene el marcador opcional?

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']); }); } }
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

¿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';
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda