1

I have a class with a function:

 export class Order {
    status: string;

    public isNew(): boolean {
        return status == 'NEW';
    }
 }

When I create a new Order I can call the function:

let order = new Order();
order.isNew();

But if retrieve an order from my backend and call the method, I get an error, order.isNew is not a function:

this.http.get('url')
.map(response => response.json() as Order)
.subscribe(order => order.isNew());

What am I doing wrong?

3 Answers 3

3

There is no logic in your sample code that some simple JSON magically becomes your Order object. You have to convert it. The 'as' operator does not do that, this is just a type cast on TypeScript level. No actual conversion is happening there.
If you wish to achieve your goal, create a constructor on Order that takes the JSON and call .map(response => new Order(response.json()))

Sign up to request clarification or add additional context in comments.

Comments

2

You are just casting your response to Order, you are not creating an object of an Order. That's why you are getting that error.

Make your class like this

export class Order {
    status: string;

    constructor(obj?: any) {
         this.status = obj && obj.status || '';
    }
    public isNew(): boolean {
        return status == 'NEW';
    }
 }


this.http.get('url')
.map(response => response.json())
.subscribe(order => {
    const new_order = new Order(order);
});

Comments

1

Because in your database, you store data, not functions. This means your function isn't saved, so when you get the response, it's not in it.

Furthermore, you're only casting the response to order, you're not creating a new one. Doing this is mainly to have autocomplete in your IDE.

If you want it to work, you need to create a constructor :

export class Order {
    constructor(public status?: string) { this.status = status; }
    public isNew(): boolean { return status == 'NEW'; }
}}

Then you need to create an object from your response :

this.http.get('url')
.map(response => new Order(response.json().status))
.subscribe(order => order.isNew());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.