I am working on an Angular component that contains a function. In this function, I need to pass an Object as a function parameter and call this function with the function parameters. It´s been a while since I have been working with Angular and at the type, "any" was the return type to use with functions; nowadays it seems to be "undefined". However, I am not sure on how to write the function call with the corresponding parameters and would appreciate any help and hints. Thanks in advance!
Here´s the component:
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);
}
}
This is the function that needs to be called in 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);
}
This is the function call in ngOnInit, where I am having the troubles in passing the paramters correctly:
public ngOnInit(): void {
this.NewWorkItem(this.interactionID, this.userdata );
}
this.userdata cannot be passed as such as function parameter; the compiler error is:
The argument of Typ "Object" cannot be assigned to the parameter of type "{ FirstName: unknown; LastName: unknown; }"
I was trying to call the function in the ngOnInit method with the corresponding parameters.
The error that I get is: The argument of Typ "Object" cannot be assigned to the parameter of type "{ FirstName: unknown; LastName: unknown; }". I cannot tell on how to pass the object as a function parameter correctly.
this.userdatais of the correct type. Your problem is herepublic userdata!: Object;there is basically never a good time to use theObjecttype, and certainly not here where you already know the shape of the object!