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

            Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

            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