1

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?

2
  • 2
    As a tiny side note, you can drop both ? true : falses from your code as === will return either true or false anyway. Commented Dec 12, 2017 at 16:20
  • It is an old code I have to refactor, Thanks for the note. Commented Dec 12, 2017 at 20:42

2 Answers 2

2

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;
        });
     });
}
Sign up to request clarification or add additional context in comments.

6 Comments

First Thanks for answer, I want to tell you that the res is an array I can't change isValid directly
This is an old code I am still modifying it, Thanks for the note.
@EbraheemAlrabee' any luck?
No, Argument of type '(users: User[]) => void' is not assignable to parameter of type '(value: void) => void'. Types of parameters 'users' and 'value' are incompatible
@EbraheemAlrabee' did you change class to interface?
|
1

Try below, that should work for you without changing user structure , and you just need to modify return type of your function to array of User

   loadAllUsers(): Observable<User[]> {
    return this.http.get("apiURL")
        .map(res => {
          return res.json().results.map(item => {
            return new User(
                  item.userId,
                item.username,
                item.password,
                item.isValid === 'Y' ? true : false,
                item.type,
                item.isValidPassword === 'Y' ? true : false
            );
          });
        });
  }

as this method returning overvable other end make use of loadAllUsers().subscribe(data=> this.userArray= data); - if it works without it leave it or if doesnt work make use of it


First of all what you are trying do is Get request to get data and you can do like this

you user class will be

export class User{
    userId: number;
    username: string;
    password: string;
    isValid: string;
    type: string;
    isValidPassword: string;
    get isValidPasswordBool():boolean {
       return this.isValidPassword=='Y';
    }
    get isValidBool():boolean {
       return this.isValid=='Y';
    }
}

call to http service like as below

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, 
             Response, ResponseContentType } from '@angular/http';

GetAllUser(): Observable<Array<User>> {
    let options = new RequestOptions({ headers: headers });
    return this._http.get("/api/admin/getUsers/",
                       options).subscribe(response => response.json());
}

6 Comments

Do you really need to set the Content-Type header here?
@serpent5 - i do set it because it then clear to person who read my code ...and he get info tha return type is going to be json...and help server to provide responseaslo
But Content-Type describes the request data, not the response data, doesn't it? Maybe you're thinking of the Accept header? It doesn't affect anything, of course - I'm just curious.
But how I can change the value of isValid to true or false depends in the server value, Thanks for the response.
@PankajParkar - sorry i just generated it from external site ..so forget to change it to class updated now
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.