Help - result.foreach is not a Function

Asked

Viewed 233 times

-1

How do I make a forEach on the return of a subscribe?

this.service.obterTodos()
.subscribe(result => {
    result.forEach(element => {
       this.usuComponent.push(element);
    });
});

Service:

obterTodos(): Observable<Usuario[]> {
    return this.httpClient.get<Usuario[]>("URL");
}

Error:

ERROR TypeError: result.forEach is not a function

Error image

Result:

inserir a descrição da imagem aqui

What additional information I need to post for you to help me?

  • 4
    1. Do not post code as image; you are already active user on the site and know that it supports source code. 2) Make sure that result is the value you hoped it would be. It’s a array?
  • You’re right, sorry for posting as image... I put my result in the post

  • try result.result.foreach

  • @Eduardovargas, does not allow, is underlined in red

  • Leo, why in the result print did you obfuscate a piece? It’s sensitive data?

  • See also the result of console.log(typeof result)

  • @Andersoncarloswoss is the real name of my object

  • 1

    Why obfuscate the object’s name? And the result of typeof?

  • To avoid confusion, I put in the user example, then they would question what is that other name there, you are not going wrong, just to avoid this kind of comment... typeof result is Object

  • There you are then. Yours result is an object, not a array. Should be a array? Do you have control over the resource that was requested on the server? It returns JSON?

  • Possibly related: What is an Array-Like?

Show 7 more comments

2 answers

0

I believe that result is an array of HTML elements, right? If yes, result is a "array type" (Array like) and not an Array itself. Try this way:

Array.from(result).forEach(element => {
    this.usuComponent.push(element);
});

or

[...result].forEach(element => {
    this.usuComponent.push(element);
});
  • For this, Array.from(result) gave Undefined, for this, [...result] gave result.Slice . is not a Function

-2

Try it this way:

this.service.obterTodos()
.subscribe((response:any)=> {
    response.result.forEach(element => {
       this.usuComponent.push(element);
    });
});
  • It’s not the same thing you suggested comments?

  • has a any in Sponse

  • 3

    Then it would be interesting to explain why it makes a difference

  • if he gives the right answer I edit the answer explaining.

  • 1

    @Eduardovargas Typeerror: Cannot read Property 'foreach' of Undefined (Undefined is the result)

  • it seems that neither your answer is an array. Nor does it have a property that is.

  • but what would be then? Because there in the print, there are several objects inside

Show 2 more comments

Browser other questions tagged

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