2

Let's say I have a class Foo:

export class Foo {
    name: string;

    printName(): void {
        console.log(this.name);
    } 
}

Now the problem is that when my FooService gets a Foo from my backend as JSON and creates a Foo object out of it, it doesn't have printName() because there's no such thing in the JSON object.

How should I arrange this (in the context of Angular 2)? Do I have to create my methods outside the class so that they just take a Foo as an argument?

In Java, for example, it's perfectly fine that DTO's have methods.

user2061057
  • 962
  • 1
  • 9
  • 20
  • Possible duplicate of [How to store a javascript function in JSON](http://stackoverflow.com/questions/36517173/how-to-store-a-javascript-function-in-json) – YounesM Mar 24 '17 at 12:18
  • What is your goal? I didn't get it. Do you want to execute your printName() mehtod on your Foo object, like this.foo.printName() ? – Emre Öztürk Mar 24 '17 at 12:22
  • I might have some more complex methods that computes something from the data fields, for example. I guess it's completely normal that a class have some methods? This is not a struct. – user2061057 Mar 24 '17 at 12:24
  • So, some external entity wants to call Foo's methods after they have been fetched from the server. – user2061057 Mar 24 '17 at 12:25
  • @YounesM This is actually the opposite. Deserializing the class from JSON "deletes" the methods. – user2061057 Mar 24 '17 at 12:27
  • JSON cannot have functions. So you cannot "serialize" your class into a JSON – YounesM Mar 24 '17 at 12:30
  • @YounesM That's why I asked how I should arrange this. – user2061057 Mar 24 '17 at 12:32

1 Answers1

7

Usually you only transfer an object with the values over http not a class instance. You have to create the class instance yourself.

export class Foo {

    constructor(name: string) {}
    printName(): void {
        console.log(this.name);
    } 
}


// data deserialized by angular from the request
let data = { name: 'John' };

let foo: Foo = new Foo(data.name);

If it helps you can make interfaces for the data you receive from the server and pass that to the constructor of the Foo class.

Note: keep in mind that there is no type casting in TS. If you are doing something like

let foo: Foo = <Foo> data;

It is a type assertion, you just tell the compiler that data is of type Foo it doesn't do anything to the data object.

toskv
  • 30,680
  • 7
  • 72
  • 74
  • 1
    yes, it serializes/deserializes stuff to an object, not a class instance. You might be confusing type assertion for type casting. :) – toskv Mar 24 '17 at 12:33