Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast object in object into Angular Class (Type)

How can I cast obj.category into Category type in example below?

I need this to set selected options in dropdown.

export class Category{
    id: number;
    name: string;

    constructor(obj: any) {
        this.id = obj.id;
        this.name = obj.name;
    }
}


export class Post {
    category: Category[];

    constructor(obj: any) {
        this.category = obj.category;
    }
}

Category service looks like this:

getCategories(): Promise<Category[]> {
    return this.http.get(this.appConfig.apiEndpoint + 'categories/').toPromise()
  .then(response => response.json().map(obj => new Category(obj)))
  .catch(this.handleError);
}

Api response:

[{"id":1,"name":"cat1"},{"id":2,"name":"cat2"}]

Template:

<select multiple name="category" [(ngModel)]="obj.post.category">
    <option  *ngFor="let category of categories" [ngValue] = "category">
       {{category.name}}
    </option>
</select>
like image 999
pelcomppl Avatar asked Dec 11 '17 07:12

pelcomppl


People also ask

How to type cast object in TypeScript?

If we want to cast the object to string data types by using toString() method we can change the object type to a string data type. We can also cast the object type to jsonby using json. parse() method we can get only the plain objects and it not used on the class object.

What is type casting in angular?

Type castings allow you to convert a variable from one type to another. In TypeScript, you can use the as keyword or <> operator for type castings.

Does TypeScript have casting?

TypeScript, on the other hand, assigns a type to every variable. Converting a variable from one type to another is possible with type casting in Typescript. Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.

How do I change a type of variable in TypeScript?

You cannot change a variable's type in TypeScript, that's just the opposite TS was made for. Instead, you can declare a variable as "any", which would be equivalent to a classic "var" variable in JS, untyped. Once a variable is declared, you will not be able to retype it.


1 Answers

Possible answer

export interface Category {
 name: string;
 prop: string;
}
export class Post {
    category: Category[];
    constructor(obj: any) {
        this.category = obj.category as Category[];
    }
}
`
like image 196
stojevskimilan Avatar answered Sep 21 '22 03:09

stojevskimilan