无法解析自定义指令的所有参数 [英] Can't resolve all parameters for custom directive
问题描述
我创建了一个自定义指令来在新选项卡中打开一个链接,在 ng serve 中运行时,它可以工作.但是,当我在 ng build --prod 中尝试时,它显示了这个错误:
I created a custom directive to open a link in a new tab, when running in ng serve, it works. However, when I tried in ng build --prod, it showed this error:
无法解析 C:/Users/myApp/src/app/directives/open-link-in-new-tab.directive.ts: ([object Object], ?) 中 OpenLinkInNewTabDirective 的所有参数中的错误.
ERROR in Can't resolve all parameters for OpenLinkInNewTabDirective in C:/Users/myApp/src/app/directives/open-link-in-new-tab.directive.ts: ([object Object], ?).
这是指令:
import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
@Directive({ selector: '[newTab]' })
export class OpenLinkInNewTabDirective {
constructor(
private el: ElementRef,
@Inject(Window) private win:Window
) {}
@Input('routerLink') link: string;
@HostListener('mousedown') onMouseEnter() {
this.win.open(this.link || 'main/default');
}
}
我已经在 tsconfig.json 中设置了 "emitDecoratorMetadata": true.先感谢您.
I set "emitDecoratorMetadata": true in tsconfig.json already. Thank you in advance.
推荐答案
这是一个已知问题,因为 Window 是一个打字稿接口.你需要通过创建一个假类来欺骗编译器,比如 WindowWrapper.ts
It is known issue because Window is an typescript interface.
You need to trick a compiler by creating a fake class say WindowWrapper.ts
@Injectable()
export class WindowWrapper extends Window { }
export function getWindow() { return window; }
app.module:
app.module:
import { WindowWrapper, getWindow } from './WindowWrapper';
providers: [
{provide: WindowWrapper, useFactory: getWindow}
],
指令:
import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
import { WindowWrapper } from './WindowWrapper';
@Directive({
selector: '[newTab]'
})
export class OpenLinkInNewTabDirective {
constructor(
private el: ElementRef,
@Inject(WindowWrapper) private win: Window) {}
@Input('routerLink') link: string;
@HostListener('mousedown') onMouseEnter() {
this.win.open(this.link || 'main/default');
}
}
check more details on that isse and that particular comment
这篇关于无法解析自定义指令的所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!