简体   繁体   中英

Angular 2 and RxJS: How to change HTTP call that returns Observable

How do I change this function to work with the JSON change described below?

The current function returns an Observable<User[]> , but with the new JSON, the new admin object has been added. The new function should successfully observe both the existing users array and the new admins array.

getData(): Observable<User[]> {
  return this.http
    .get('www.example.com/api/users)
    .map((r: Response) => r.json().assets.users as User[]);
}

JSON returned from /api/users

{
"assets": {
    "users": [
        // user objects
    ]
}

...now returns two arrays, users and admins .

{
"assets": {
    "users": [
        // array of user objects
    ],
    "admins": [
        // array of admin objects
    ]

}

Please assume that my code does have User and Admin classes already created that correctly reflect the properties of the related JSON objects returned.

Well, you have a few options how to return the data:

getData(): Observable<User[]> {
  return this.http
    .get('www.example.com/api/users')
    .map((r: Response) => { 
         const assets = r.json().assets;
         return {
             users: assets.users as User[],
             admins: assets.admins as Admin[]
         }
     });
}

Or like this:

getData(): Observable<User[]> {
  return this.http
    .get('www.example.com/api/users')
    .map((r: Response) => { 
         return [
             assets.users as User[],
             assets.admins as Admin[]
         ]
     });
}

Or like this:

getData(): Observable<User[]> {
  return this.http
    .get('www.example.com/api/users')
    .map((r: Response) => { 
         return [
             ...assets.users as User[],
             ...assets.admins as Admin[]
         ]
     });
}

If you want to return both users and admins in the same array, the following code should do the trick:

getData(): Observable<User[]> {
  return this.http
    .get('www.example.com/api/users)
    .map((r: Response) => {
        var results = r.json();
        return results.assets.users.concat(results.assets.admins);
    }
}

With the following data:

{
"assets": {
    "users": [
        { "name": "bob" }, { "name": "john" }
    ],
    "admins": [
        { "name": "jill" }, { "name": "donald" }
    ]

}

The result would be equal to:

[ { "name": "bob" }, { "name": "john" }, { "name": "jill" }, { "name": "donald" } ]

As explained in my comment for @Maximus answer, .map() is used to transform an array into a new one, which is why you want to feed a function to .map() to tell it what array you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM