打字稿:未定义的静态变量问题

时间:2019-04-30 23:42:19

标签: javascript typescript

我不明白为什么会发生下一个问题。具有相同结构的代码在任何其他面向对象的语言(例如C#或Java)中都可以正常工作。 我使用Typescript编写Node.Js应用程序。

所以我有一个带有两个静态变量的类ServiceLocator

//ServiceLocator.ts
export class ServiceLocator {
    public static dataRepository: IDataRepository = new DataRepository();
    public static authService: IAuthService = new AuthService();
}

使用第一个静态变量从第二个变量进行分类。这样看起来:

//AuthService.ts
const dataRepository: IDataRepository = ServiceLocator.dataRepository;
export class AuthService implements IAuthService {
...
}

但是一旦我尝试获得authService链接,就这样:

//AuthController.ts
const authService: IAuthService = ServiceLocator.authService;
export class AuthController {

    public async signIn(request: Request, response: Response) {
        ..
    }
..
}

我收到一个错误:

 TypeError: Cannot read property 'dataRepository' of undefined

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您在这里有一个循环参考。为了构造AuthService 模块,您需要一个完全构造的ServiceLocator类。但是,JavaScript需要一个完全构造的AuthService模块才能构造ServiceLocator类。切换实例化顺序仅会导致错误从ServiceModule <cint>(到Java主义),遵循“未捕获的TypeError:未定义不是构造函数”的字样。

解决方案是简单地使依赖项变得懒惰:

//AuthService.ts
const dataRepositoryReference: IDataRepository = import('./ServiceLocator')
  .then(({ ServiceLocator }) => ServiceLocator.dataRepository);
export class AuthService implements IAuthService {
  public async findUserByUsername(username: UserName) {
    const dataRepository = await dataRepositoryReference;
    // ... snip ...
  }
}
相关问题