繁体   English   中英

在 Angular 库中创建时,instanceof 返回 false

[英]instanceof returns false when created in Angular Library

在 Angular 库中创建对象时, instanceof返回 false。

import {
  Component,
  OnInit
} from '@angular/core';
import {
  FormControl,
} from '@angular/forms';
import {genControl} from 'test-lib';                        // import a function from my own library.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{

  constructor() {
  }

  ngOnInit() {

    const fcA = genControl();                               // Create a FormControl in Angular Library
    const fcB = new FormControl('');

    if (fcA instanceof FormControl) {
      console.log('fcA is instanceof FormControl');
    } else {
      console.log('fcA is not instanceof FormControl');     // displays this.
    }

    if (fcB instanceof FormControl) {
      console.log('fcB is instanceof FormControl');         // displays this.
    } else {
      console.log('fcB is not instanceof FormControl');
    }

  }
}

test-lib是一个 Angular 库项目构建作为这篇文章 genControl的代码如下。

import {FormControl} from '@angular/forms';

export function genControl(): FormControl {
  return new FormControl('');
}

上面代码的输出如下。

fcA is not instanceof FormControl
fcB is instanceof FormControl

为什么fcA不是FormControl的实例? 我应该如何修复fcA将是FormControl实例?

主项目AppComponent和 Angular 库genControl Angular 版本相同,即 9.1.11。

正如@andriishupta 提到的,这是因为应用程序和库从不同的文件导入FormControl 我应该在tsconfig.json指定paths如下。

  "compilerOptions": {
        :
    "paths": {
      "@angular/*": [
        "./node_modules/@angular/*"
      ]
    }
  },

暂无
暂无

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

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