簡體   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