Angular 5 models httpClient type casting

前端 未结 2 1755
忘掉有多难
忘掉有多难 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条回答
  •  Happy的楠姐
    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(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.

提交回复
热议问题