为何触发TypeScript错误TS2395:RegisterComponent声明需全导出或全本地?
解决TypeScript错误TS2395:RegisterComponent合并声明不一致问题
问题描述
运行以下Angular代码时触发TypeScript错误TS2395:Individual declarations in merged declaration 'RegisterComponent' must be all exported or all local:
import { RegisterComponent } from './register.component'; import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService } from '../../../../src/app/services/auth.service'; import { User } from '../../../Models/User'; @Component({ selector: 'app-register', templateUrl: './register.component', }) export class RegisterComponent implements OnInit { repeatpass: string = 'none'; constructor(private authService: AuthService, private router: Router) { } ngOnInit(): void { } goToMenu() { this.router.navigate(['componenets/food-menu']); } registerForm = new FormGroup({ firstname: new FormControl("",[Validators.required,Validators.minLength(2), Validators.pattern("[a-zA-Z].*")]), lastname: new FormControl("",[Validators.required,Validators.minLength(2), Validators.pattern("[a-zA-Z].*")]), email: new FormControl("", [Validators.required,Validators.email]), mobile: new FormControl("", [Validators.required,Validators.pattern("[0-9]*"),Validators.minLength(10),Validators.maxLength(10),]), gender: new FormControl("", [Validators.required]), pwd: new FormControl("", [Validators.required,Validators.minLength(6),Validators.maxLength(15)]), rpwd: new FormControl(""), }); registerSubmited() { { this.repeatpass = 'none' let modal: User = {} as User; this.authService.registerUser(modal); } } get FirstName(): FormControl { return this.registerForm.get("firstname") as FormControl; } get LastName(): FormControl { return this.registerForm.get("lastname") as FormControl; } get Email(): FormControl { return this.registerForm.get("email") as FormControl; } get Mobile(): FormControl { return this.registerForm.get("mobile") as FormControl; } get Gender(): FormControl { return this.registerForm.get("gender") as FormControl; } get PWD(): FormControl { return this.registerForm.get("pwd") as FormControl; } }
错误原因
代码第一行的import { RegisterComponent } from './register.component';是问题核心:当前文件正是RegisterComponent的定义文件,自导入操作会让TypeScript识别出两个同名的RegisterComponent声明——一个是导入的外部导出声明,一个是当前文件的本地导出声明,违反了TypeScript合并声明必须统一为全部导出或全部本地的规则,因此触发TS2395错误。
解决方案
直接删除第一行的自导入语句即可,修改后的代码开头如下:
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService } from '../../../../src/app/services/auth.service'; import { User } from '../../../Models/User';
另外可以顺便修复代码中的两处小问题:
registerSubmited方法内存在一对冗余的大括号,建议删除router.navigate中的路径拼写错误:componenets应改为components
内容的提问来源于stack exchange,提问作者user123456
相关产品推荐
相关产品推荐

