0

I'm not sure how to integrate my restful API´s with the HTTP Angular client, this is my HTTP Angular client implementation:

getList(): Promise<any> {
this.http.get<any>(this.url).toPromise()
  .then(
  data =>  {
    console.log(data);
  }
);

And this is my API JSON response structure:

{
    "eeeeee": {
        "qqq": [
            {
                "aaa": "fff",
                "zzz": "bbb",
                "yyy": "mmm",
                "xxx": "nnn"
            },
            {
                "aaa": "aaa",
                "zzz": "zzzz",
                "yyy": "yyyy",
                "xxx": "ccc"
            }
        ]
    }
}
1

1 Answer 1

1

Try to use an service for your API calls e.g apiService, then using your service in every component that you want. In addition, it's recommended to use Observables instead of Promises. So, Try something like this:

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  private REST_API_SERVER = "http://localhost:3000";

  constructor(private http: HttpClient) { }

  getList(): Promise<any> {
     return this.http.get<any>(this.url);
  }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  public list: any;

  constructor(private apiService: ApiService ) { }

  ngOnInit() {

    this.apiService.getList().subscribe((data: any[])=>{
      console.log(data);
      this.list= data;
    })  
  }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey @ng-hobby, I already have a service in my angular app and in the previous version of my app I used Observables, the problem is, I had the necessity to change my rest API response, before my api returned a List but now returns a Map<String, Object[]> Above I posted my API JSON example, like you posted it will not work, because DATA is and object that have an object inside, and in this second object it has an array list
Ok, what's the problem? in your Components you cant get the inner object by data.eeeeee e.g. console.log(data.eeeeee) or get the array and do any process that you want. If you think you will have more transformation on your data you can use a second service as a factory and do the processing staff there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.