简体   繁体   中英

How to map object value to observable array

I am receiving a JSON object from an http get request that has the array of objects I want in its value property. As I am new to Angular 7 and Rxjs, I can't figure out how to map the array to my objects.

I am getting the data back as any, which brings back the data, to verify it is what I want. I have gotten arrays of objects back from other API, but they have not been in the value attribute of a parent object. When I use the tap message to the console, I see what I want to push to my array of objects, but I don't know the mapping syntax.

The JSON below is what I am getting back from the getTfsUsers() method from my user.service.ts.

Below that is the class (assignee.ts) I want to map the data to.

I would like getTfsUsers() to return an observable array of Assignee objects fro

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#directoryObjects(displayName,mail)",
    "@odata.nextLink": "https://graph.microsoft.com/v1.0/groups/blahblah",
    "value": [
        {
            "@odata.type": "#microsoft.graph.user",
            "displayName": "Deer, John",
            "mail": "deer.john@myplace.org"
        },
        {
            "@odata.type": "#microsoft.graph.user",
            "displayName": "Doe, Jane",
            "mail": "doe.jane@myplace.org"
        },
        {
            "@odata.type": "#microsoft.graph.user",
            "displayName": "Fawn, Mike",
            "mail": "fawn.mike@myplace.org"
        }
     ]
}


getTfsUsers(): Observable<any>{
    const uri = `${this.groupsBaseUri}/${this.tfsUsersGroupId}/members/${this.displayNameMailFields}`;
    return this.http.get<any>(uri)
      .pipe(
        catchError((error: HttpErrorResponse) => { return throwError(error); })
      );
  }
export class Assignee {
    mail: string;
    displayName: string;
}

Is there a way to map the value attribute from the object being returned to an array of Assignees?

You can use RxJS's map operator for that purpose, and have it nested within your pipe() . You will need to import the map operator on the top of your service, as shown below. Do note that it is different from JavaScript's Array.map() .

import { map } from 'rxjs/operators';
.
.

getTfsUsers(): Observable<any>{
    const uri = `${this.groupsBaseUri}/${this.tfsUsersGroupId}/members/${this.displayNameMailFields}`;
    return this.http.get<any>(uri)
      .pipe(
        map(data => data['value'].map(obj => {
          return {
            mail: obj.mail,
            displayName: obj.displayName
          };
        })),
        catchError((error: HttpErrorResponse) => { return throwError(error); })
      );
  }

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