zilcuanu
zilcuanu

Reputation: 3715

angular model objects not mapped correctly

I am invoking a REST API and returning Observable<User[]> as follows:

User.service.ts

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(private httpClient:HttpClient) { }

  getAllUsers():Observable<User[]>{
    return this.httpClient.get<User[]>('https://jsonplaceholder.typicode.com/users');
  }
}

In My component class, I am subscribing to and assigning to the instance variable:

UserComponent.ts

private users:User[];
constructor(private userService:UserService) { }

  ngOnInit() {
    this.userService.getAllUsers()
     .subscribe(users => this.users = users) 
 }

I have also created my model class User.ts

export class User{

    constructor(
        private _id:number,
        private _username:string,
        private _email:string,
        private _phone:string
    ){}

    get id():number{return this._id;}
    set id(id:number){this._id = id;}

    get username():string{return this._username;}
    set username(username:string){this._username = username;}

    get email():string{return this._email;}
    set email(email:string){this._email = email;}

    get phone():string{return this._phone;}
    set phone(phone:string){this._phone = phone;}
}

The below are my questions:

  1. When I print the this.users inside the ngOnInit method after fetching the users from the service, I am also getting all the properties which are not mapped in my User.ts class. example: address, website etc.

  2. Is this behavior correct, as I am getting typescript support to call only the properties defined in the model class inside the component, but able to see all the properties while printing.

  3. Is there a way to fetch only the properties from the service, since, my application might want only a subset of data from the service and I do not want to load the entire json data into the component?

Is there something I am missing here.

Upvotes: 1

Views: 1347

Answers (1)

rh16
rh16

Reputation: 1073

Yes, this is correct behavior.

When you use a generic type on the httpClient.get method you are casting the result to that type, not constructing an instance of the class.

As far as only getting the fields you need returned to you goes, this will depend on the API you are calling to.

The json placeholder API used in your example does not support this.

If you want the objects in your component to be instances of the Users class, you can instantiate the class when you assign them:

 ngOnInit() {
    this.userService.getAllUsers()
     .subscribe(users => this.users = users.map(user => new User(
        user.id,
        user.username,
        user.email,
        user.phone
      )
    )) 
 }

Upvotes: 2

Related Questions