Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda