angular model objects not mapped correctlyHow do I cast a JSON object to a typescript classHow to parse a JSON object to a TypeScript ObjectAngular HTML bindingAngularJS 2 Typescript interfaceclass variable is undefined after subscribing observable in lifecycle hookHow to update the page from the service in ionic2?Getting an object array from an Angular serviceUpdating a user list when a user is created in Angular 2ngOninit not getting called angular 2 expressAngular 2 - Typescript - Rx - Interface member undefinedAngular http requestunable to access FormGroup from my service in angular 5

Multiplicative persistence

Is this toilet slogan correct usage of the English language?

What is the evidence for the "tyranny of the majority problem" in a direct democracy context?

What is Cash Advance APR?

Does a 'pending' US visa application constitute a denial?

Is it possible to put a rectangle as background in the author section?

Can I sign legal documents with a smiley face?

How much character growth crosses the line into breaking the character

The screen of my macbook suddenly broken down how can I do to recover

Has any country ever had 2 former presidents in jail simultaneously?

How can Trident be so inexpensive? Will it orbit Triton or just do a (slow) flyby?

Added a new user on Ubuntu, set password not working?

C++ debug/print custom type with GDB : the case of nlohmann json library

How can "mimic phobia" be cured or prevented?

Count the occurrence of each unique word in the file

Drawing ramified coverings with tikz

Start making guitar arrangements

Is it better practice to read straight from sheet music rather than memorize it?

copy and scale one figure (wheel)

Calculating Wattage for Resistor in High Frequency Application?

Should I outline or discovery write my stories?

Intuition of generalized eigenvector.

What is this called? Old film camera viewer?

A social experiment. What is the worst that can happen?



angular model objects not mapped correctly


How do I cast a JSON object to a typescript classHow to parse a JSON object to a TypeScript ObjectAngular HTML bindingAngularJS 2 Typescript interfaceclass variable is undefined after subscribing observable in lifecycle hookHow to update the page from the service in ionic2?Getting an object array from an Angular serviceUpdating a user list when a user is created in Angular 2ngOninit not getting called angular 2 expressAngular 2 - Typescript - Rx - Interface member undefinedAngular http requestunable to access FormGroup from my service in angular 5













1















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():numberreturn this._id;
set id(id:number)this._id = id;

get username():stringreturn this._username;
set username(username:string)this._username = username;

get email():stringreturn this._email;
set email(email:string)this._email = email;

get phone():stringreturn 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.










share|improve this question






















  • Not sure but this and this will help:)

    – Prashant Pimpale
    Mar 8 at 4:43
















1















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():numberreturn this._id;
set id(id:number)this._id = id;

get username():stringreturn this._username;
set username(username:string)this._username = username;

get email():stringreturn this._email;
set email(email:string)this._email = email;

get phone():stringreturn 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.










share|improve this question






















  • Not sure but this and this will help:)

    – Prashant Pimpale
    Mar 8 at 4:43














1












1








1


1






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():numberreturn this._id;
set id(id:number)this._id = id;

get username():stringreturn this._username;
set username(username:string)this._username = username;

get email():stringreturn this._email;
set email(email:string)this._email = email;

get phone():stringreturn 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.










share|improve this question














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():numberreturn this._id;
set id(id:number)this._id = id;

get username():stringreturn this._username;
set username(username:string)this._username = username;

get email():stringreturn this._email;
set email(email:string)this._email = email;

get phone():stringreturn 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.







angular typescript






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 4:37









zilcuanuzilcuanu

1,09431953




1,09431953












  • Not sure but this and this will help:)

    – Prashant Pimpale
    Mar 8 at 4:43


















  • Not sure but this and this will help:)

    – Prashant Pimpale
    Mar 8 at 4:43

















Not sure but this and this will help:)

– Prashant Pimpale
Mar 8 at 4:43






Not sure but this and this will help:)

– Prashant Pimpale
Mar 8 at 4:43













1 Answer
1






active

oldest

votes


















2














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
)
))






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056813%2fangular-model-objects-not-mapped-correctly%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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
    )
    ))






    share|improve this answer





























      2














      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
      )
      ))






      share|improve this answer



























        2












        2








        2







        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
        )
        ))






        share|improve this answer















        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
        )
        ))







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 8 at 5:12

























        answered Mar 8 at 4:49









        rh16rh16

        555314




        555314





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056813%2fangular-model-objects-not-mapped-correctly%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme