如何创建 class TypeScript 的实例?
How to create instance of class TypeScript?
我有以下 class:
export declare class FlashMessagesService {
show: (text?: string, options?: Object) => void;
grayOut: (value: boolean) => void;
}
然后我尝试创建 class:
的实例
import { FlashMessagesService } from 'angular2-flash-messages';
let _flashMessagesService = new FlashMessagesService();
它引发错误:
Cannot read property 'show' of undefined
我用这个library
您应该在 :
之前为您的 class 创建一个构造函数
export class Flashmessages {
...
//other vars
constructor(){
this.myvar = "value";
}
}
我不认为你的问题是 typescript 本身,而是 angular 依赖注入和组件的组成方式。
如果您查看正在使用的包的源代码,您会发现 show
函数实际上是由 FlashMessagesComponent and not by FlashMessagesService itself.
实现的
因此,要在没有 angular 依赖注入的情况下自行创建它的实例,这将很棘手,因为您还需要提供抽象实例 class ChangeDetectorRef
,它本身可能依赖于其他东西,所以它可能很快就会变得非常混乱。
类似下面的代码可能会帮助您开始使用它,但它与您想要在现实世界中使用的东西相去甚远。
import { FlashMessagesService, FlashMessagesComponent } from 'angular2-flash-messages';
let _flashMessagesService = new FlashMessagesService();
let component = new FlashMessagesComponent(_flashMessagesService, { detectChanges: () => {}} );
console.log(_flashMessagesService.show) // [Function show]
编辑:
我直接在 SO 上编码,无法测试它(抱歉 :( ),现在更彻底地检查它似乎 FlashMessagesComponent it not exported,所以我不清楚如何创建一个不使用 FlashMessagesModule
和 angular 依赖注入生命周期的实例。
我有以下 class:
export declare class FlashMessagesService {
show: (text?: string, options?: Object) => void;
grayOut: (value: boolean) => void;
}
然后我尝试创建 class:
的实例 import { FlashMessagesService } from 'angular2-flash-messages';
let _flashMessagesService = new FlashMessagesService();
它引发错误:
Cannot read property 'show' of undefined
我用这个library
您应该在 :
之前为您的 class 创建一个构造函数export class Flashmessages {
...
//other vars
constructor(){
this.myvar = "value";
}
}
我不认为你的问题是 typescript 本身,而是 angular 依赖注入和组件的组成方式。
如果您查看正在使用的包的源代码,您会发现 show
函数实际上是由 FlashMessagesComponent and not by FlashMessagesService itself.
因此,要在没有 angular 依赖注入的情况下自行创建它的实例,这将很棘手,因为您还需要提供抽象实例 class ChangeDetectorRef
,它本身可能依赖于其他东西,所以它可能很快就会变得非常混乱。
类似下面的代码可能会帮助您开始使用它,但它与您想要在现实世界中使用的东西相去甚远。
import { FlashMessagesService, FlashMessagesComponent } from 'angular2-flash-messages';
let _flashMessagesService = new FlashMessagesService();
let component = new FlashMessagesComponent(_flashMessagesService, { detectChanges: () => {}} );
console.log(_flashMessagesService.show) // [Function show]
编辑:
我直接在 SO 上编码,无法测试它(抱歉 :( ),现在更彻底地检查它似乎 FlashMessagesComponent it not exported,所以我不清楚如何创建一个不使用 FlashMessagesModule
和 angular 依赖注入生命周期的实例。