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>
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.
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.
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.
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.
Possible answer
export interface Category {
name: string;
prop: string;
}
export class Post {
category: Category[];
constructor(obj: any) {
this.category = obj.category as Category[];
}
}
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With