我正在编写服务,运行该服务时出现以下错误。 有问题的部分是:
<a [href]="fileUrl" [download]="fileName" mat-menu-item (click)="download(fileId)">Download</a>
错误:
import { Configuration } from "./Configuration";
import { BooksApplication } from "./application/BookApplication";
import { PersistenceBookRepository } from "./application/PersistenceBookRepository";
import { DatabaseAccessor } from "./database/DatabaseAccessor";
export class Context {
public readonly configuration: Configuration;
public constructor(configuration: Configuration) {
this.configuration = configuration;
}
private readonly databaseAccessor = new DatabaseAccessor(
this.configuration.databaseConfiguration
);
private readonly bookRepository = new PersistenceBookRepository(
this.databaseAccessor
);
private readonly bookService = new BooksApplication(this.bookRepository);
}
我已经检查了从Typescript生成的代码,它看起来像这样:
TypeError: Cannot read property 'databaseConfiguration' of undefined
at new Context (/sandbox/src/Context.ts:14:24)
at Object.<anonymous> (/sandbox/src/index.ts:6:17)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
error Command failed with exit code 1.
您可以看到// ...
var Context = (function () {
function Context(configuration) {
this.databaseAccessor = new DatabaseAccessor_1.DatabaseAccessor(this.configuration.databaseConfiguration);
this.bookRepository = new PersistenceBookRepository_1.PersistenceBookRepository(this.databaseAccessor);
this.bookService = new BooksApplication_1.BooksApplication(this.bookRepository);
this.configuration = configuration;
}
return Context;
}());
// ...
位于末尾,因此this.configuration = configuration;
失败了。
我做错了什么还是Typescript中有错误?
我试图更改类成员的顺序,但结果相同。
我有一个项目在这里重现该问题:https://codesandbox.io/embed/644k5kwr4r
谢谢。
答案 0 :(得分:1)
根据spec proposal¹,这实际上是正确的启动顺序:
在评估字段初始值设定项并将字段添加到实例时:
基类:在构造函数执行的开始,甚至在参数分解之前。
派生类:在super()返回之后。 (由于可以灵活地调用super(),因此许多实现都为此情况创建了一个单独的不可见的initialize()方法。)
TLDR:类字段首先在构造函数体之前执行。
不过,您可以只将初始化移到构造函数中。
¹因为TS是JS的超集,所以它也必须符合ES规范。