Angular 5 models httpClient type casting

前端 未结 2 1731
忘掉有多难
忘掉有多难 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:16

    You'll need to use a property, not a method. The returned object is really a json object, and there is no such thing as "getName()" method (despite your effort to add a type information). Try something like this:

    export interface Ingredient {
        strin: string,
        amount: number,
        created_at: string
    }
    
    
    httpClient.get<Ingredient>(url).subscribe(
         (igredient) => {
              console.log(igredient.amount);
    });
    

    EDIT: You need to provide a type information based on the expected json object. If the returned json object has attributes, strin, amount, and created_at, then you need to define a type that is compatible with the expected json object.

    0 讨论(0)
  • 2021-01-27 19:34

    In angular 5, You can do this:

    export interface Deserializable<T> {
        deserialize(input: any): T;
      }
    
    export class Ingredient implments Deserializable<Ingredient>{
    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<Ingredient>(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.

    0 讨论(0)
提交回复
热议问题