问题描述
在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
是一个this post的Angular Library项目构建。 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所述,这是因为应用程序和lib从不同的文件中导入了FormControl
。
我应该在paths
中指定tsconfig.json
,如下所示。
"compilerOptions": {
:
"paths": {
"@angular/*": [
"./node_modules/@angular/*"
]
}
},