-1

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?

Ant
  • 129
  • 1
  • 11
  • have you imported the httpclient into the class and the httpclientmodule into the imports? and why did you bind `this` to the http call? – mast3rd3mon Dec 03 '18 at 14:54
  • i also dont understand why you have a shared component? components typically (if not always) have a html page to accompany them – mast3rd3mon Dec 03 '18 at 15:00
  • Yes, I add httpClient to class and httpClientModile to imports. I have that shared _module and components in it because I have much more modules which should have access to shared_component – Ant Dec 03 '18 at 15:02
  • @Ant Did you try the below? Does that work for you? – Amit Chigadani Dec 03 '18 at 15:24

1 Answers1

0

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);
}
Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98