Angular EventEmitter类型错误:预期0个类型参数却传入1个
Angular: Fixing "Expected 0 type arguments, but got 1" and Type Mismatch Errors with EventEmitter
我刚解决了和你一模一样的问题!咱们来一步步搞定它:
问题回顾
你遇到了两个关联的TypeScript错误:
- 当你声明带有类型参数的EventEmitter时:
报错:@Output() newUserInfoCompleteEvent = new EventEmitter<boolean>();Expected 0 type arguments, but got 1 - 去掉
<boolean>后,调用emit方法时:
又报错:this.newUserInfoCompleteEvent.emit(this.newUserInfoComplete);Argument of type 'boolean' is not assignable to parameter of type 'string'
错误根源
看你的组件导入语句,你错误地从protractor导入了EventEmitter:
import { EventEmitter } from 'protractor';
Protractor的EventEmitter是为端到端测试设计的,它不支持泛型类型参数,而且默认只接受string类型的参数——这就是两个错误的核心原因!
修复步骤
修正EventEmitter的导入来源:把
EventEmitter从@angular/core导入,而不是protractor。修改你的导入语句:import { Component, OnInit, Output, EventEmitter } from '@angular/core';同时删掉单独的
import { EventEmitter } from 'protractor';这一行。保留正确的泛型类型参数:你的EventEmitter声明是对的,继续保留
<boolean>:@Output() newUserInfoCompleteEvent = new EventEmitter<boolean>();验证emit调用:现在调用
this.newUserInfoCompleteEvent.emit(this.newUserInfoComplete)时,TypeScript会正确识别boolean类型,不会再报错。
修正后的完整组件代码
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { slideToRight } from '../../../../router.animations'; import { Router, ActivatedRoute, UrlSegment } from '@angular/router'; @Component({ selector: 'app-new-user-input', templateUrl: './new-user-input.component.html', styleUrls: ['./new-user-input.component.css'], animations: [slideToRight()] }) export class NewUserInputComponent implements OnInit { newUserInfoComplete: boolean = false; @Output() newUserInfoCompleteEvent = new EventEmitter<boolean>(); constructor(private router: Router, r: ActivatedRoute) { r.url.subscribe((s: UrlSegment[]) => { console.log("url", s); }); } ngOnInit() { } sendNewUserInfoComplete(){ this.newUserInfoCompleteEvent.emit(this.newUserInfoComplete); } displaySibling() { console.log(this.router); this.router.navigate(['../', { outlets: { newuserorginfo: ['newuserorginfo'] } }]) } closeBlade() { this.router.navigate([{ outlets: { newuserinput: null } }]); } }
内容的提问来源于stack exchange,提问作者imnickvaughn
相关产品推荐
相关产品推荐

