簡體   English   中英

如何實例化Angular 2模型

[英]How to instantiate model Angular 2

我正在為CRUD產品創建一個非常基礎的Angular 2應用程序。 我有一個CreateProductComponent,但是在實例化我不想在視圖上使用的模型時遇到了麻煩。 我收到此錯誤:

在此處輸入圖片說明

這是我的代碼:

創建-product.component.ts

import { Component, OnInit }  from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import { Product } from '../product'
import { ProductService } from '../product.service'

@Component({
    moduleId: module.id,
    selector: 'app-create-product',
    templateUrl: 'create-product.html',
    styleUrls: ['create-product.css'],
})
export class CreateProductComponent {

    model: new Product(1,'2',1); <- error on this line

    constructor(private productService: ProductService) { }

    addProduct() {        

        //this.productService.addProduct(this.product);
    }
}

product.ts

export class Product {

    constructor(
        public ID: number,
        public Name: string,
        public Price: number
    ) { }   
}

理想情況下,我想創建一個空產品或具有默認值的產品,以便當視圖中的表單中填充有產品數據時,此數據將向下傳遞給產品。 有誰知道如何解決這個問題?

它應該是

model = new Product(1,'2',1);

問題是您的語法有點差。 您應該使用以下任何一種:

這將創建一個實例化值為Product的屬性。

export class CreateProductComponent {

    // Define model, declare type, and assign/instantiate.
    model = new Product(1,'2',1);

    constructor(private productService: ProductService) { }
}

或將屬性model定義為“ Product類型但不為其分配值的模型。 相反,它是在構造函數中分配的。

export class CreateProductComponent {

    // Define model, declare type
    model: Product;

    constructor(private productService: ProductService) {
        this.model = new Product(1,'2',1);
    }
}

另外,您甚至可以更加明確,即使不需要,因為可以輕松推斷出類型。

export class CreateProductComponent {

    // Define model, declare type, and assign/instantiate.
    model: Product = new Product(1,'2',1);

    constructor(private productService: ProductService) { }
}

我強烈建議您在此處使用一些出色的文檔以及一個REPL游樂場

您正在CreateProductComponent中創建一個字段。 用“ =”代替“:”

model = new Product(1,'2',1); <- error on this line

在打字稿術語中, “:”表示您要為已定義的變量聲明類型。

“ =”表示您正在為變量分配一個值。

但是在這里,您要做的是代替分配值,而是嘗試聲明一個值(根據語法,這是不正確的)

因此,您可以直接分配一個值,例如

model = new Product(1,'2',1);

否則,您可以先為變量聲明類型,然后以這兩種方式之一分配值(我個人更喜歡這種方式)

model: Product = new Product(1,'2',1);

要么

model: Product;
model = new Product(1,'2',1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM