Skip to content Skip to sidebar Skip to footer

How To Get Array Of Object Instead Of Object In Angular?

can you please tell me how to get array of objects instead of object in angular 2.I am hitting a service and getting a object as a response . getUsers(): Observable

Solution 1:

You can use the map operator to extract the data array from the original response. See this stackblitz for a demo.

Models:

exportinterfaceUserModelResponse {
  page: number;
  per_page: number;
  total: number;
  total_pages: number;
  data: Array<UserModel>
}

exportinterfaceUserModel {
  id: number;
  first_name: string;
  last_name: string;
  avatar: string;
}

Service:

getUsers(): Observable<Array<UserModel>> {
  returnthis.http.get<UserModelResponse>(this.configUrl).pipe(
    map(x => x.data),
    catchError(this.handleError)
  );
}

Component:

ngOnInit() {
  this.userDetail.getUsers().subscribe((response: Array<UserModel>) => {
    console.log(response);
    this.users = response;
  }, (error) => {
    console.log('error', error);
  }, () => {
    console.log('complete');
  });
}

Solution 2:

You have to transform the result from the getUsers method:

 getUsers(): Observable<UserModel[]> {
    returnthis.http.get<UserModelPage>(this.configUrl)
    .pipe(map(res => res.data), catchError(this.handleError));
  }

with map:

import { catchError, map } from'rxjs/operators';

where UserModelPage is something like this:

interfaceUserModelPage{
  data: UserModel[]
}

Solution 3:

The following would change in your user-detail.service.ts

getUsers(): Observable<HttpResponse<UserModel>> {
    returnthis.http.get<HttpResponse<UserModel>>(this.configUrl).pipe( 
      map((res:any) => {
        return res.data;
        })
    );
  }

and the following would change in your app.component.ts

ngOnInit() {
    this.userDetail.getUsers().subscribe((response: any) => {
      console.log(response);
      this.users = response;
    }, (error) => {
      console.log('error', error);
    }, () => {
      console.log('complete');
    });
  }

I included a working representation here in case you might need it.

Post a Comment for "How To Get Array Of Object Instead Of Object In Angular?"