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

            Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

            Posting a File and Associated Data to a RESTful WebService preferably as JSON2019 Community Moderator ElectionREST URI convention - Singular or plural name of resource while creating itUploading both data and files in one form using Ajax?How do I upload a file with metadata using a REST web service?REST API - file (ie images) processing - best practicesSpring: JSON data and file in the same requestREST API Put large dataPosting a file and JSON data to Spring rest serviceRESTful Web Service Upload/Download Large Data With JSONREST API Design sending JSON data and a file to the api in same requestPost JSONArray to REST servicePUT vs. POST in RESTParsing values from a JSON file?JavaScript/jQuery to download file via POST with JSON dataHow do I upload a file with metadata using a REST web service?How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?Separate REST JSON API server and client?what's the correct way to send a file from REST web service to client?How do I write JSON data to a file?What is “406-Not Acceptable Response” in HTTP?REST API - file (ie images) processing - best practices

            How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page