简体   繁体   English

如何创建TypeScript类的实例?

[英]How to create instance of class TypeScript?

I have the following class: 我有以下课程:

export declare class FlashMessagesService {
    show: (text?: string, options?: Object) => void;
    grayOut: (value: boolean) => void;
}

And I try to create instance of class: 我尝试创建类的实例:

 import { FlashMessagesService } from 'angular2-flash-messages';
    let _flashMessagesService = new FlashMessagesService();

It invoke an error: 它调用一个错误:

Cannot read property 'show' of undefined

I use this library 我用这个图书馆

I don't think you problem is typescript per se, but with angular dependency injection and how components are composed instead. 我不认为您的问题本身就是打字稿,而是角度依赖注入以及组件的组成方式。

If you look at the source code of the package you are using you will see that show function is actually implemented by the FlashMessagesComponent and not by FlashMessagesService itself . 如果查看正在使用的包的源代码,您将看到show函数实际上是由FlashMessagesComponent实现的,而不是由FlashMessagesService本身实现的

So to create an instance of it on your own without angular's dependency injection it is going to be tricky because you would also need to provide an instance of the abstract class ChangeDetectorRef , which itself might depend on other stuff, so it might get really messy pretty quickly. 因此,要自行创建它的实例而不使用angular的依赖项注入将非常棘手,因为您还需要提供一个抽象类ChangeDetectorRef的实例,该类本身可能依赖于其他内容,因此可能会变得非常混乱很快。

something like the code bellow might help you to start playing with it, but it is far from something you would want to use in the real world. 像下面这样的代码可能会帮助您开始使用它,但是与您在现实世界中想要使用的东西相去甚远。

import { FlashMessagesService, FlashMessagesComponent } from 'angular2-flash-messages';
let _flashMessagesService = new FlashMessagesService();
let component = new FlashMessagesComponent(_flashMessagesService, { detectChanges: () => {}} );
console.log(_flashMessagesService.show) // [Function show]

EDIT: 编辑:

I coded directly here on SO and could not test it (sorry :( ), now checking it more thoroughly it seems that FlashMessagesComponent it not exported , so I don't clearly see a way for you to create an instance without using FlashMessagesModule and angular dependency injection lifecycle. 我在此处直接在SO上编码,无法对其进行测试(对不起:(),现在更彻底地对其进行检查,似乎它没有导出FlashMessagesComponent ,因此我没有清楚地看到一种无需使用FlashMessagesModule和angular即可创建实例的方法依赖项注入生命周期。

You should create a constructor for your class before : 您应该在创建类之前创建一个构造函数:

export class Flashmessages { 
    ...
    //other vars
    constructor(){
        this.myvar = "value";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM