0

我想将现有库集成到我的打字稿项目中。我想声明和使用一个(外部)单例对象。

示例:在 xyz.js 中,将声明以下对象:

var mxUtils = {
    /* some fancy code */
    findNode: function(node, attr, value)
    {
        // even more fancy code
        return node;
    }
};

在运行时,有一个全局单一的 mxUtils 实例。由于这是一个外部库,我不想在 typescript 中实现或重写整个库。

现在我试图声明这个单例,但我失败了。

我尝试了这段代码,将对象声明为全局变量。

实用程序.d.ts:

declare interface ImxUtils { 
    findNode(node:any, attr:string, value:string):any;
}

declare var mxUtils: ImxUtils;

我的编译器对此完全满意,但在运行时,mxUtils 未定义

main.ts:

// some fancy things
export class fancyComponent implements OnInit {
    // some magic here...
    var tmpNode = mxUtils.findNode(aNode, aString1, aString2);    
}

即使我的调试器列出了一个全局 mxUtils 对象。

谁可以帮我这个事?

请备注:* xyz.js 已被引用且存在。例如

xyz.js

function mxEventObject(name)
{
//
}

mxEventObject.prototype.getName = function()
{
    return this.name;
};

实用程序.d.ts

declare class mxEventObject {
    constructor(name: string);
    getName: () => string;
}

主要的.ts

export class fancyComponent implements OnInit {
    // some magic here...
    var tmpEvent = new mxEventObject(aSampleString);

}

将按预期工作。

由于有一个名为 mxUtils 的全局对象,但我无法在我的 fancyComponent 导出中访问该对象,我想存在范围问题。

4

1 回答 1

0

在 Angular 中更好地中继 DI(依赖注入)系统来处理对象创建并将这些对象注入到组件中,您需要创建一个 Angular 服务并将此服务添加到 AppModule 组件装饰器中的提供者列表中。

mx-utils.service.ts

export class MxUtilsService {

  /* some fancy code */
  public findNode(node:any, attr:any, value:any) {
    // even more fancy code
    return node;
  }
}

app.module.ts

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [MxUtilsService]
})
export class AppModule { }

应用程序组件.ts

import { Component } from '@angular/core';
import { MxUtilsService } from './mx-utils.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private _mxUtilsService: MxUtilsService) {
    console.log(this._mxUtilsService);
    console.log(this._mxUtilsService.findNode({node:1},'node',1));
  }
}

添加到 appModule(root) 中的提供者列表的任何服务都被视为单例, MxUtilsService 将创建一个,并且当您注入另一个组件时将是同一个对象

stackblitz 演示

为什么您的对象未定义,您需要添加xyz.js到脚本列表中.angular-cli.json

于 2018-09-20T08:31:56.697 回答