Cannot read Property 'map' of Undefined error in Browse (Angular)

Asked

Viewed 328 times

-1

Hello, When I access my page, error appears in Browse: Typeerror occurred Typeerror: Cannot read Property 'map' of Undefined. My code containing the call . map() is like this:

export class LancamentoCadastroComponent implements OnInit {

categorias = [];  

constructor(private categoriaService: CategoriaService,
          private errorHandler: ErrorHandlerService) { }

ngOnInit() {
this.carregarCategorias();


carregarCategorias() {
return this.categoriaService.listarTodas()
  .then(categorias => {
    this.categorias = categorias.map(c => ({ label: c.nome, value: c.codigo }));
  })
  .catch(erro => this.errorHandler.handle(erro));
}
} 

I even get a message on errorHandler on my E. ErrorHandler is like this:

@Injectable()
export class ErrorHandlerService {


constructor(private toasty: ToastyService) { }

handle(errorResponse: any) {
let msg: string;

if (typeof errorResponse === 'string') {
  msg = errorResponse;

} else if (errorResponse instanceof Response
    && errorResponse.status >= 400 && errorResponse.status <= 499) {
  let errors;
  msg = 'Ocorreu um erro ao processar a sua solicitação';

  try {
    errors = errorResponse.json();

    msg = errors[0].mensagemUsuario;
  } catch (e) { }

  console.error('Ocorreu um erro', errorResponse);

} else {
  msg = 'Erro ao processar serviço remoto. Tente novamente.';
  console.error('Ocorreu um erro', errorResponse);
}

this.toasty.error(msg);
}
}

Could you please give me a north where I am missing? It implies that you do not know this method . map(). Thank you.

  • 1

    Caro Victor, listarTodas is returning empty and so . map will not work, because then failed to get anything, go to the method listarTodas in class CategoriaService and fix this.

  • Hello William, thank you for the return. I checked this and really was missing an import (import 'rxjs/add/Operator/toPromise'). Thanks for the help. Is there any way I can get a more specific return for this case? For example, have an error message saying 'map is empty' or something? Thank you!

  • But the problem is not in the map, as I said before, it is no then, or better, in what sends to your file, so just check if the value sent in then is "empty", like: if (!categorias || !categorias.length) { ... mensagem de erro ...} else { this.categorias = categorias.map(c => ({ label: c.nome, value: c.codigo })); }, There must be something very wrong in your class, because if it was "correct" it was to fall in CATCH and not in THEN.

1 answer

0

Found the problem:

An import was missing:

import 'rxjs/add/operator/toPromise';

in category.service.ts I arrived at this result after the return of @Guilherme Nascimento to tell me that . map() was empty.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.