Can not read property of undefined Angular 2

2

Good morning.

Currently I have a view, from which I recover a data that happened to a component that calls a service. The data passes from the view to the function of the component by means of a click event without any problem. But when you call the service function it shows an error that the property is undefined.

View:

<input #search type="text" ng-model="search">
<button (click)="searchIt(search.value)" class="button is-primary">Search</button>

Component function:

searchIt(id: string){
    this.myService.getIt(id)
                        .subscribe(
                            res => {
                                this.content = res;
                            },
                            err => {
                                console.log(err);
                            }
                        );
}

Service function (even if it does not even call it):

 getIt(id: string):  Observable<content[]>{
     console.log("Servicio: " + key);
     return this.http.get(this.url + "/" + id)
                .map(res => res.json())
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
 };

Let's see if anyone can help me.

    
asked by Findelias 24.02.2017 в 13:12
source

1 answer

2

You have to inject the service.

constructor(public myservice: myService) {

}

and you make reference to the service

this.myservice.getIt(id)
         .subscribe(
           res => {
               this.content = res;
           },
           err => {
               console.log(err);
           }
         );
    
answered by 24.02.2017 / 23:57
source