javascript - 使用我自己的模型类型属性模拟 Angular2/typescript 的数据

标签 javascript angular typescript

我是 Angular2 世界的新手。为了学习 Angular,我遵循了不同的教程,现在我尝试建立一个商店来了解更多信息。但我马上就卡住了。

我正在尝试将此模型添加到 Angular 中: enter image description here

但我没有成功。我收到不同的错误,例如。

TypeError: Cannot read property 'description' of undefined and error TS2322: Type '{ ... }' is not assignable to type 'Product[]'.Type ...

这是我到目前为止得到的:

产品类型属性模型

export class ProductTypeAttribute {
id: number;
name: string;
content: string;
}

产品类型模型

import { ProductTypeAttribute } from './product-type-attribute.model';

export class ProductType {
    id: number;
    name: string;
    description: string;
    attributeTypes: ProductTypeAttribute[];
}

产品型号

import { ProductType} from './product-type.model';

export class Product  {
    id: number;
    name: string;
    description: string;
    image: string;
    price: number;
    type: ProductType;
}

模拟产品

import { Product } from './product.model';
import { ProductType } from './product-type.model';
import { ProductTypeAttribute } from './product-type-attribute.model';

export const productTypeAttributes: ProductTypeAttribute[] = [
    {
        id: 1,
        name: 'Kleur',
        content: 'test'
    },
    {
        id: 2,
        name: 'test',
        content: 'test'
    },
    {
        id: 3,
        name: 'test',
        content: 'test'
    },
    {
        id: 4,
        name: 'test',
        content: 'test'
    }
];

export const productTypeAttributes2: ProductTypeAttribute[] = [
    {
        id: 5,
        name: 'Kleur',
        content: 'test'
    },
    {
        id: 6,
        name: 'test',
        content: 'test'
    },
    {
        id: 7,
        name: 'test',
        content: 'test'
    },
    {
        id: 8,
        name: 'test',
        content: 'test'
    }
];

export const productType: ProductType =
    {
        id: 1,
        name: 'Type 1',
        description: 'Description of type 1',
        attributeTypes: productTypeAttributes
    };

export const productType2: ProductType =
    {
        id: 2,
        name: 'Type 2',
        description: 'Description of type 2',
        attributeTypes: productTypeAttributes2
    };

export const products: Product[] = [
    {
        id: 1,
        name: 'Product 1',
        description: 'Description of product 1',
        image: 'https://www.google.nl/imgres?imgurl=https%3A%2F%2Fangular.io%2Fresources%2Fimages%2Flogos%2Fangular2%2Fangular.svg&imgrefurl=https%3A%2F%2Fangular.io%2F&docid=bJoyJcb-C12SHM&tbnid=G_BYSyR7DGpqqM%3A&vet=1&w=800&h=800&bih=1060&biw=1060&q=angular2&ved=0ahUKEwjdrq6it87RAhUEExoKHdXlAYIQMwgcKAAwAA&iact=mrc&uact=8',
        price: 15.15,
        type: productType
    },
    {
        id: 2,
        name: 'Product 2',
        description: 'Description of product 2',
        image: 'https://www.google.nl/imgres?imgurl=https%3A%2F%2Fangular.io%2Fresources%2Fimages%2Flogos%2Fangular2%2Fangular.svg&imgrefurl=https%3A%2F%2Fangular.io%2F&docid=bJoyJcb-C12SHM&tbnid=G_BYSyR7DGpqqM%3A&vet=1&w=800&h=800&bih=1060&biw=1060&q=angular2&ved=0ahUKEwjdrq6it87RAhUEExoKHdXlAYIQMwgcKAAwAA&iact=mrc&uact=8',
        price: 15.15,
        type: productType
    },
    {
        id: 3,
        name: 'Product 3',
        description: 'Description of product 3',
        image: 'https://www.google.nl/imgres?imgurl=https%3A%2F%2Fangular.io%2Fresources%2Fimages%2Flogos%2Fangular2%2Fangular.svg&imgrefurl=https%3A%2F%2Fangular.io%2F&docid=bJoyJcb-C12SHM&tbnid=G_BYSyR7DGpqqM%3A&vet=1&w=800&h=800&bih=1060&biw=1060&q=angular2&ved=0ahUKEwjdrq6it87RAhUEExoKHdXlAYIQMwgcKAAwAA&iact=mrc&uact=8',
        price: 15.15,
        type: productType2
    }
];

产品-服务

import { Injectable } from '@angular/core';

import { Product } from './../shared/product.model';
import { products } from './../shared/mock-products';

@Injectable()
export class ProductService {
    getProducts(): Promise<Product[]> {
        return Promise.resolve(products);
    }

    getProduct(id: number): Promise<Product> {
        return this.getProducts().then(products => products.find(product => product.id === id));
    }
}

产品组件

import { Component, OnInit } from '@angular/core';
import { Product } from './../shared/product.model';
import { ProductService } from './../product/product.service';

@Component({
    selector: 'product',
    template: require('./product.component.html'),
    providers: [ProductService]
})

export class ProductComponent implements OnInit {
    product: Product;

    constructor(private productService: ProductService) { }

    getProduct(): void {
        this.productService.getProduct(1).then(product => this.product = product);
    }

    ngOnInit(): void {
        this.getProduct();
    }
}

产品 HTML

<div class="product">
<div class="header">
        <h1>{{product?.name}}</h1>
        <h4></h4>
</div>

<figure>
    <img src="{{product?.image}}">
</figure>

<section>
    <p>{{product?.description}}</p>
    <details>
        <summary>Product Features</summary>
        <ul>
            <li *ngFor="let productAttribute of product?.type?.attributeTypes">
                {{productAttribute?.name}}
            </li>
        </ul>
    </details>
    <button>Buy Now</button>
</section>

我希望我能很好地解释我的问题,希望你们能帮我解决这个问题。

更新 enter image description here

*更新** 好吧,现在事情变得疯狂了。 当我这样做时

export const products: ({ id: number;description: string;image: string;price: number;type: Object } |
{ id: number;name: string;description: string;image: string;price: number;type: Object })[] = [
{
    id: 1,
    description: "Description of product 1",
    image: "https://www.google.nl/imgres?imgurl=https%3A%2F%2Fangular.io%2Fresources%2Fimages%2Flogos%2Fangular2%2Fangular.svg&imgrefurl=https%3A%2F%2Fangular.io%2F&docid=bJoyJcb-C12SHM&tbnid=G_BYSyR7DGpqqM%3A&vet=1&w=800&h=800&bih=1060&biw=1060&q=angular2&ved=0ahUKEwjdrq6it87RAhUEExoKHdXlAYIQMwgcKAAwAA&iact=mrc&uact=8",
    price: 15.15,
    type: productType
},
{
    id: 2,
    name: "Product 2",
    description: "Description of product 2",
    image: "https://www.google.nl/imgres?imgurl=https%3A%2F%2Fangular.io%2Fresources%2Fimages%2Flogos%2Fangular2%2Fangular.svg&imgrefurl=https%3A%2F%2Fangular.io%2F&docid=bJoyJcb-C12SHM&tbnid=G_BYSyR7DGpqqM%3A&vet=1&w=800&h=800&bih=1060&biw=1060&q=angular2&ved=0ahUKEwjdrq6it87RAhUEExoKHdXlAYIQMwgcKAAwAA&iact=mrc&uact=8",
    price: 15.15,
    type: productType
},
{
    id: 3,
    name: "Product 3",
    description: "Description of product 3",
    image: "https://www.google.nl/imgres?imgurl=https%3A%2F%2Fangular.io%2Fresources%2Fimages%2Flogos%2Fangular2%2Fangular.svg&imgrefurl=https%3A%2F%2Fangular.io%2F&docid=bJoyJcb-C12SHM&tbnid=G_BYSyR7DGpqqM%3A&vet=1&w=800&h=800&bih=1060&biw=1060&q=angular2&ved=0ahUKEwjdrq6it87RAhUEExoKHdXlAYIQMwgcKAAwAA&iact=mrc&uact=8",
    price: 15.15,
    type: productType2
}

它没有给出错误,但不显示名称。

最佳答案

实际测试了你的代码,似乎只有异步问题。尝试使用安全运算符:?(也称为 elvis-operator),如下所示:

<h1>{{product?.name}}</h1>

另一种选择是像这样使用*ngIf:

<h1 *ngIf="product">{{product.name}}</h1>

关于 elvis-operator 的更多信息 here .这在 Angular (2) 应用程序中非常方便,因为我们一直在处理异步操作,因为(通常)在接收数据之前呈现 View 。

如果您更喜欢 *ngIf 这也有效,应用程序不会抛出错误,因为您包裹在其中的代码仅在存在数据时呈现,在本例中为您的 产品对象。

工作 Plunker

您可以改为将类更改为接口(interface),因此:

export interface Product  {
    id: number;
    name: string;
    description: string;
    image: string;
    price: number;
    type: ProductType;
}

或将构造函数添加到您的类中:

export class Product  {
    constructor(
      public id: number,
      public name: string,
      public description: string,
      public image: string,
      public price: number,
      public type: ProductType
    ) { }
}

关于javascript - 使用我自己的模型类型属性模拟 Angular2/typescript 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41765329/

相关文章:

typescript - 在 TypeScript 中提示抽象类

javascript - GMap 轴承旋转平稳运动(改变轴承值时避免抖动效果)

javascript - 使用 Sequelize 根据请求正文中的项目数创建动态 where 子句?

filter - RxJs 可观察到的 : Execute function if empty/filtered

Angular-CLI 代理在 docker 中不工作

highcharts - angular2-highcharts Highcharts 导出模块

typescript - 使用 SweetAlert2 显示加载警报而无需交互

javascript - 如何修复失败的 NextJS 导出 - 在本地工作正常,但导出时失败,令人沮丧 :(

JavaScript - 当我更改链接的 href 时未定义链接

typescript :typeof checkin 列表项不起作用