我正在做一个包含函数的Angular组件。在这个函数中,我需要传递一个Object作为函数参数,并使用函数参数调用这个函数。我已经有一段时间没有使用Angular和"任意"类型了。是用于函数的返回类型;如今,它似乎是"不确定的"。但是,我不确定如何使用相应的参数编写函数调用,并将感谢任何帮助和提示。提前感谢!
组件:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-root', // eslint-disable-line @angular-eslint/component-selector
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
public interactionID: number=0;
@Input()
public userdata!: Object;
constructor() {
// Called first time before the ngOnInit()
}
public ngOnInit(): void {
this.NewWorkItem(this.interactionID, this.userdata );
}
public NewWorkItem(interactionID: unknown, userData: { FirstName: unknown; LastName: unknown }): void {
console.log('NewWorkItem call',interactionID,userData);
const event: Event = new CustomEvent ('wde.newWorkItem', {
detail: {
FirstName: userData.FirstName,
LastName: userData.LastName,
InteractionID: interactionID
},
bubbles: true,
cancelable: true,
composed: false,
});
console.log('NewWorkItem event',event);
window.dispatchEvent(event);
}
}
这是ngOnInit中需要调用的函数:
public NewWorkItem(interactionID: unknown, userData: { FirstName: unknown; LastName: unknown }): void {
console.log('NewWorkItem call',interactionID,userData);
const event: Event = new CustomEvent ('wde.newWorkItem', {
detail: {
FirstName: userData.FirstName,
LastName: userData.LastName,
InteractionID: interactionID
},
bubbles: true,
cancelable: true,
composed: false,
});
console.log('NewWorkItem event',event);
window.dispatchEvent(event);
}
这是ngOnInit中的函数调用,我在正确传递参数时遇到了麻烦:
public ngOnInit(): void {
this.NewWorkItem(this.interactionID, this.userdata );
}
。Userdata不能作为函数参数传递;编译错误是:
The argument of Typ "Object" cannot be assigned to the parameter of type "{ FirstName: unknown; LastName: unknown; }"
我试图用相应的参数调用ngOnInit方法中的函数。我得到的错误是:type "Object"不能分配给类型为"{ FirstName: unknown; LastName: unknown; }"
的参数。我不知道如何正确地将对象作为函数参数传递。
可以导出为单独的界面:
export interface IUserData { FirstName: unknown; LastName: unknown }
然后:
@Input() public userdata!: IUserData;
...
public NewWorkItem(interactionID: unknown, userData: IUserData);
首先需要为userData创建一个类型:
type UserData = { FirstName: string; LastName: string };
那么你应该使用UserData
类型来输入userData属性和参数。
属性:
@Input() public userdata!: UserData;
参数:
public NewWorkItem(interactionID: unknown, userData: UserData): void {