Search code examples
angularhttpget

get array of object angular CLI


Hi I'm trying to fetch data from a get request in angular. I have a class Apartment that looks like this:

export class Apartment {

  id: number;
  address: string;

  constructor(id: number, name: string) {

      this.id = id;
      this.name = name;
 }
 }

A service

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

 baseURL = 'http://localhost:3000';

 constructor(private httpClient: httpClient) {}

 getApartments() {
     return this.httpClient.get(this.baseURL + '/apartments');
 }
 }

A component

 export class SettingsComponent implements OnInit {

 apartments: Apartment[] = [];

 constructor(private apiService: Service) {
   // todo: fetch data here...
}}

I have a rest api that works and a json file to read that look like this:

 {
   "id" : 0,
   "address: "not assinged yet"
 }

How can I read and cast the data to an array of Apartment?


Solution

  • If you do not have any class specific methods, I would not use a class here myself, just an interface. But if you do want to have a class and create instances of your data to that class, you need to map your data, here assumingly you get an array. Also tell angular what you are getting in your request:

     getApartments() {
       return this.httpClient.get<Apartment[]>(this.baseURL + '/apartments').pipe(
         map((arr) => arr.map(x => new Apartment(x.id, x.address)))
       )
     }
    

    Then in your component:

    ngOnInit() {
      this.apiService.getApartments()
        .subscribe((data: Apartment[]) => this.apartments = data);
    }
    

    But as I mention, I would use an interface if there are no methods in the class:

    export interface Apartment {
      id: number;
      address: string;
    }
    

    and the get request, simply:

     getApartments() {
       return this.httpClient.get<Apartment[]>(this.baseURL + '/apartments')
     }
    

    and subscribe in the component mentioned above.