[英]instanceof function parameter returns false in Typescript/Angular
[英]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.