angular2 map data as specific object type

前端 未结 4 1987
梦如初夏
梦如初夏 2021-01-04 13:50

I created a very simple app based on the Angular2 tutorial.

To start, I have a very simple \"Book\" model:

 /**
 * book model
 */
export class Book          


        
4条回答
  •  逝去的感伤
    2021-01-04 14:20

    From https://angular.io/guide/http#requesting-a-typed-response

    To specify the response object type, first define an interface with the required properties. Use an interface rather than a class, because the response is a plain object that cannot be automatically converted to an instance of a class.

    Always receive response using interface because only thing that's happening is mapping fields, and you cannot use class if you have instance function which will throw error when you use that object.

    product.getPrice is not a function
    

    Example

    interface ProductInterface {
      id: number;
      name: string;
      price: number;
    }
    
    class Product implements ProductInterface {
      id: number;
      name: string;
      price: number;
      
      constructor(productData: ProductInterface) {
        this.id = product.id;
        this.name = product.name;
        this.price = product.price;
      }
      
      public getPrice(): string {
        return this.price + " INR";
      }
    }
    
    class ProducService {
      ...
      ...
    
    
      getProduct(): Observable {
        return this.http.get('assets/product.json').pipe(map(data => new Product(data))); 
      }
    
      getProductWithoutMappingToClass(): Observable {
        return this.http.get('assets/product.json');
      } // Throw runtimerror ctx_r1.product.getPrice is not a function
    }
    
    

提交回复
热议问题