I need to pass method of my service as parameter. Folder structure looks like this:
-app.module.ts
-- MODULE
|___main_component
-- SHARED MODULE
|___shared_component
|___shared_service
My shared_service contains only one method and looks like this:
@Injectable({providedIn: 'root'})
export class SharedService
{
methodUrl = "some_http_url";
constructor(private http: HttpClient)
{
}
getStatuses() : Observable<any>
{
return this.http.get<any>(this.methodUrl);
}
}
In my main_component I create a object called data with function as parameter
createData(){
this.data = this.SharedService.getStatuses.bind(this);
}
and pass that data to my shared_component as @Input() parameter.
And when I am trying to call it from my ngOnOnit()
export class SharedComponent implements OnInit{
@Input()
data: any;
result: any;
constructor() {}
ngOnOnit(){
this.data.subscribe((response) => this.result = response)
}
}
the error message "TypeError: Cannot read property 'get' of undefined" appears in console. I figured it out that that error refers to return this.http.get(this.methodUrl); because of HttpClient is undefined.
Did anybody confront that error before and could share the knowledge about it?
You should probably pass the object SharedService
and not this
as the context to bind()
method because getStatuses
appears to be in service and not the component.
createData(){
this.data = this.SharedService.getStatuses.bind(this.SharedService);
}