[英]Instantiate new typed object from domain model in Angular 2
每次我嘗試從域模型實例化一個新對象時,我使用 TypeScript 的 Angular 2 (RC) 應用程序都會中斷,並出現錯誤:
錯誤:類型錯誤:無法讀取 undefined(...) 的屬性“原型”
export class Reservation {
public ReservationId: number;
public SeatingId: number;
public EventId: number;
// ...
constructor() {}
}
然后在我的組件中我使用:
import { Reservation } from '../models/models';
....
let booking = new Reservation();
這個和其他模型對象由 http 服務實例化,沒有問題,作為參數傳遞,並且通常在整個應用程序中使用 - 都沒有問題,但是當我在應用程序的任何地方添加“new Reservation()”時,我收到了這個錯誤。
我已經看到很多使用這種語法的例子,我還嘗試創建一個可注入的工廠服務來返回新對象,以及我能想到的所有其他方式,但無論在我的應用程序中的哪個位置,我都添加了這一行引導期間中斷。 在構建過程中沒有顯示 TypeScript 錯誤或任何內容。
更新:問題似乎只發生在從另一個文件導入的類中。 我創建了一個虛擬示例,當該類與我的組件在同一個文件中時,它可以工作,但是如果該類是從另一個文件導入的,則它不會,即這有效:
import { Component, OnInit } from '@angular/core';
//import { Foo } from '../models/models';
export class Foo {
public Name: string;
public Score: number;
}
@Component({
selector: 'foo',
template: `
<h1>{{bar.Name}}</h1>
`,
directives: []
})
export class FooComponent implements OnInit {
bar : Foo;
constructor() { }
ngOnInit() {
this.bar = new Foo();
this.bar.Name = "Foobar";
}
}
這不會:
import { Component, OnInit } from '@angular/core';
import { Foo } from '../models/models';
@Component({
selector: 'foo',
template: `
<h1>{{bar.Name}}</h1>
`,
directives: []
})
export class FooComponent implements OnInit {
bar : Foo;
constructor() { }
ngOnInit() {
this.bar = new Foo();
this.bar.Name = "Foobar";
}
}
在這兩種情況下, Foo 類是相同的。 文件的路徑也是正確的。 我的編輯器是 VS Code,並且沒有構建錯誤或解析導入類的問題,或者以 new Foo() 以外的任何其他方式使用類;
更新 2:
我發現我的 ts 文件中的 import 語句沒有轉換為相應編譯的 js 文件中的 require 語句,因此我的被編譯為 models.js 的 models.ts 沒有被瀏覽器加載,我猜將解釋為什么我不能實例化其中包含的任何類。
更新 3:
上次更新可能是一個紅鯡魚。 如果我嘗試注入我想在組件構造函數中使用的類,則會根據需要在 js 文件中添加 models.js 並由瀏覽器加載,但會發生完全相同的錯誤。
我有一個類似的問題。 我解決它的方法是為變量設置默認值。
export class Reservation {
public ReservationId: number = null;
public SeatingId: number = null;
public EventId: number = null;
// ...
constructor() {}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.