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:
When I print the
this.users
inside thengOnInit
method after fetching the users from the service, I am also getting all the properties which are not mapped in myUser.ts
class. example: address, website etc.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.
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.