How to process JSON that has an object array as property with Observable (Angularjs)?

Asked

Viewed 674 times

0

I have an API that returns objects JSON as follows:

{
    "data": [
        {
            "nome": "objeto1"
        },
        {
            "nome": "objeto2"
        },
    ]
}

However, when receiving the objects in the service, I can’t just pick up the objects, and it returns to me an object that has as property a variable data array of objects, which is extremely confusing and difficult to handle.

When giving a console.log in the object received, came to me the following return:

{data: Array(2)}

Service (detail: I had to change the kind of return everywhere it appears Objeto for any):

const JSON_PATH = environment.path;

@Injectable({
  providedIn: 'root'
})
export class ContaCorrenteService{

  constructor(private http: HttpClient){ }

  public listAll():Observable<Objeto[]>{
    return this.http.get<Objeto[]>(BANK_ACCOUNT_PATH);
    }
}

Expected object:

export interface Objeto{
    nome: string;
    /* demais propriedades */
}

In short: how to convert that received object into the Httpclient call to array (so that instead of I pass the object as objetos.data in the foreach, pass just as objetos)?

  • 1

    It is not at all clear your question, which Angular are you using? In the code seems to be Angular but in the question put Angularjs, and what you intend to do with the return of the Api?

  • Angular 8 (I got confused when writing the tags). I only want to convert the return to a array of objects before subscribing to the components using the service, instead of the object with array that I’m getting

  • What appears when you do it: console.log(JSON.stringify(objeto), null, ' ', false) ?

  • {"data":[{"id":1,"name":"Ms. Bert Denesik"},{"id":2,"name":"Mstgopaijdqoruehjgpza"}]} null false

  • Is the API yours? If so, print the result without the date. Or create an object to manipulate API results with the 'data' and any array[].

1 answer

1


export interface Objeto{
    nome: string;
    /* demais propriedades */
}

export interface ObjetoPayload {
 data: Objeto[];
}

@Injectable({
  providedIn: 'root'
})
export class ContaCorrenteService{

  constructor(private http: HttpClient){ }

  public listAll():Observable<Objeto[]>{
    return this.http.get<ObjetoPayload>(BANK_ACCOUNT_PATH).pipe(map((res: ObjetoPayload) => res.data));
    }
}

If you just want to get the date, it solves your problem.

Browser other questions tagged

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