Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为外部库制作一个薄薄的Angular/Typescript包装,而不需要太多的重复?_Angular_Typescript - Fatal编程技术网

如何为外部库制作一个薄薄的Angular/Typescript包装,而不需要太多的重复?

如何为外部库制作一个薄薄的Angular/Typescript包装,而不需要太多的重复?,angular,typescript,Angular,Typescript,我需要为一个外部库编写一个服务包装器,这样我就可以将它注入到我的应用程序的各个组件中。我当前的代码如下所示: import * as externalLibrary from 'widgetManager'; import { Injectable } from '@angular/core'; @Injectable() export class WidgetService { realService: externalLibrary.Service; constructor()

我需要为一个外部库编写一个服务包装器,这样我就可以将它注入到我的应用程序的各个组件中。我当前的代码如下所示:

import * as externalLibrary from 'widgetManager';
import { Injectable } from '@angular/core';

@Injectable()
export class WidgetService {
  realService: externalLibrary.Service;

  constructor() {
    this.realService = new externalLibrary.Service();
  }

  create(params) {
    this.realService.create(params);
  }

  read(params) {
    this.realService.read(params);
  }

  update(params) {
    this.realService.update(params);
  }

  delete(params) {
    this.realService.delete(params);
  }

}

真正的库有比上面多得多的方法,但通常我只想给我的类编写一个薄包装器,它可以直接将参数原封不动地传递出去。如何在不为每个方法编写重复定义的情况下实现这一点?

您不必创建包装器类。你只需要让它可以注射

export const SERVICE = new InjectionToken<externalLibrary.Service>('Service');

@NgModule({
    providers: [
        {
            provide: SERVICE, 
            useValue: new externalLibrary.Service()
    ]
});

谢谢如果我想将externalLibrary.Service缩短为单个令牌,比如externalLibService,该怎么办?有没有办法做到这一点?@Stewart你可以创建一个令牌并使用它。您不必提供TypeScript类型。如果你愿意,你可以随便用。
@Component({...})
export class MyComponent {
    public constructor(@Inject(SERVICE) service: externalLibrary.Service) {
        // more code here
    }
}