从Angular的RESTful服务中获取大数据中的特定字段的最佳做法是什么?

时间:2019-09-21 07:57:02

标签: angular typescript angular7 datamapper

我正在调用RESTful服务,该服务返回的数据包含很多字段,但是我想使接口像DTO一样仅携带我需要的数据。 我使用了来自rxjs的管道和地图,但我不知道这是否是最佳实践:

通常返回的数据:

[
  {
    "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"
    }
  },
  {...}
]

我只需要它的数据:

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

用户界面:

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

用户服务:

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,
            };
          })
        )
      );
  }
}

1 个答案:

答案 0 :(得分:2)

我找到了答案:

用户界面:

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
}

用户服务:

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