I have the following files in an Angular 2 app:
Injectable service
@Injectable()
export class CompanyService{
constructor(private http:Http){}
public test():any{
return this.http.get('http://echo.jsontest.com/title/ipsum/content/blah')
.map(res => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
Component
@Component({
templateUrl: 'company.html',
providers: [CompanyService]
})
export class CompanyPage{
constructor(private companyServ:CompanyService){}
//This method is used from a submit for using ngSubmit
public onSubmit():void{
this.companyServ.test().subscribe(data => {
console.log('Data', data);
}, err => {
console.error('Error', err);
}, console.log('End'));
}
}
When the view is rendered and method onSubmit
is called, I get the following error:
Any information about the error would be much appreciated.
The solution was to change the data type that returns the test()
method of class CompanyService
:
Injectable service
public test():Observable<any>{
return this.http.get('http://echo.jsontest.com/title/ipsum/content/blah')
.map(res => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
Component
I deleted the 3 parameter because Observable<any>
allows only 2 parameters: The success function and the error function
public onSubmit():void{
this.companyServ.test().subscribe(data => {
console.log('Data', data);
}, err => {
console.error('Error', err);
});
}