![](/img/trans.png)
[英]How to create Angular 5 HttpClient instance in Typescript class
[英]How to create instance of class TypeScript?
我有以下課程:
export declare class FlashMessagesService {
show: (text?: string, options?: Object) => void;
grayOut: (value: boolean) => void;
}
我嘗試創建類的實例:
import { FlashMessagesService } from 'angular2-flash-messages';
let _flashMessagesService = new FlashMessagesService();
它調用一個錯誤:
Cannot read property 'show' of undefined
我用這個圖書館
我不認為您的問題本身就是打字稿,而是角度依賴注入以及組件的組成方式。
如果查看正在使用的包的源代碼,您將看到show
函數實際上是由FlashMessagesComponent實現的,而不是由FlashMessagesService本身實現的 。
因此,要自行創建它的實例而不使用angular的依賴項注入將非常棘手,因為您還需要提供一個抽象類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 ,因此我沒有清楚地看到一種無需使用FlashMessagesModule
和angular即可創建實例的方法依賴項注入生命周期。
您應該在創建類之前創建一個構造函數:
export class Flashmessages {
...
//other vars
constructor(){
this.myvar = "value";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.