Angular 5 models httpClient type casting

前端 未结 2 1730
忘掉有多难
忘掉有多难 2021-01-27 18:44

I declare a model in ingredient.model.ts

export class Ingredient {
 constructor(private name: string, public amount: number) {}

 getName() { return this.name }
         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-27 19:34

    In angular 5, You can do this:

    export interface Deserializable {
        deserialize(input: any): T;
      }
    
    export class Ingredient implments Deserializable{
    constructor(private name: string, public amount: number) {}
    
    deserialize(input: any): Project {
        Object.assign(this, input);
        // do nested thing here -pop arrays of nested objects and create them
        }
        return this;
      }
    

    now in your service:

      httpClient.get(url).pipe(map(elem=>this.foo(elem)))
     .subscribe((igredient) => {console.log(igredient.getName());
       });
    
    foo(ingredient:Ingrdient){
     var i = new Ingridiant().desrialize(ingredient)
    }
    

    after the map you will have the Ingradient class, not the object.

提交回复
热议问题