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:
export interface UserModelResponse {
  page: number;
  per_page: number;
  total: number;
  total_pages: number;
  data: Array<UserModel>
}
export interface UserModel {
  id: number;
  first_name: string;
  last_name: string;
  avatar: string;
}
Service:
getUsers(): Observable<Array<UserModel>> {
  return this.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[]> {
    return this.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:
interface UserModelPage {
  data: UserModel[]
}
Solution 3:
The following would change in your user-detail.service.ts
getUsers(): Observable<HttpResponse<UserModel>> {
    return this.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?"