angulartypescriptangular7datamapper

What's the best practice to fetch specific fields from big data coming from RESTful service in Angular?


I am calling RESTful service which return data contains a lot of fields, but I want to make interface like DTO to carry only data I need it. I used pipe & map from rxjs but I dont know is this tha best practice or not:

The returned data in usual:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {...}
]

The data I only need it:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz"
  },
  {...}
]

user Interface:

export interface User {
    id?:number,
    name?:string,
    email?:string,
    username?:string
}

user Service:

export class UsersService {
  constructor(private http: HttpClient) {}

  getAllUsers(): Observable<User[]> {
    return this.http.get<User[]>("https://jsonplaceholder.typicode.com/users")
      .pipe(
        map((data: User[]) =>
          data.map((item: User) => {
            return {
              id: item.id,
              name: item.name,
              email: item.email,
              username: item.username,
            };
          })
        )
      );
  }
}

Solution

  • I found the answer:

    user Interfaces:

    interface User {
      id: number,
      name: string,
      email: string,
      username: string
    }
    
    interface UserResponse {
      id: number;
      name: string;
      username: string;
      email: string;
      address: any; // lazily using 'any' here
      phone: string;
      website: string;
      company: any; // lazily using 'any' here
    }
    

    user Service:

    export class MyService {
      constructor(private http: HttpClient) { }
    
      getData(): Observable<User[]> {
        return this.http.get<UserResponse[]>('https://jsonplaceholder.typicode.com/users')
          .pipe(
            map((data: UserResponse[]) =>
              data.map((item: UserResponse) => {
                return <User>{
                  id: item.id,
                  name: item.name,
                  email: item.email,
                  username: item.username,
                };
              })
            )
          );
      }
    }
    

    Stackblitz example