Search code examples
jsonangularangular-httpclient

HttpClient - Mapping Json array result with changing some values


I have a problem in using the new HttpClient.

Before, I was able to map a users Json array into User[] by using reduce, as the following:

export class User {
    constructor(
        public userId: number,
        public username: string,
        public password: string,
        public isValid: boolean,
        public type: string,
        public isValidPassword: boolean) {
    }
}

public loadAllUsers() {
    return this.http
        .post('/api/admin/getUsers/', 0)
        .map((res: any) => {
            return new User(
                res.userId,
                res.username,
                res.password,
                res.isValid === 'Y',
                res.type,
                res.isValidPassword === 'Y'
            );
        })
        .reduce((x, y) => { x.push(y); return x; }, <any[]>[]);
}

and that is a part of /api/admin/getUsers/ response:

[
  {
    "userId": 1,
    "username": "Ebraheem Alrabee",
    "password": "827ccb0eea8a706c4c34a16891f84e7b",
    "isValid": "Y",
    "type": "admin",
    "isValidPassword": "Y"
  },
  {
    "userId": 4,
    "username": "Sami",
    "password": "827ccb0eea8a706c4c34a16891f84e7b",
    "isValid": "Y",
    "type": "user",
    "isValidPassword": "Y"
  }, ...
]

I have tried this:

public loadAllUsers() {
    return this.http
        .post<User[]>('/api/admin/getUsers/', 0);
}

But I still want to use map instead of direct deserialize into User[], Because there is values I want to change like isValid.

How I can do the same thing with new HttpClient, Any one can help?


Solution

  • You could use .map there, to transform/modify isValid flag. Also I'd suggest you change User class to interface.

    public loadAllUsers(): Observable<User[]> {
        return this.http
         .post<any>('/api/admin/getUsers/', 0)
         .map((res: any) =>
            return <User[]>res.map(item => {
               item.isValid = item.isValid === 'Y';
               item.isValidPassword = item.isValidPassword === 'Y';
               return item;
            });
         });
    }