2016-10-21 39 views
-1

我已经在角2应用以下文件:Angular2 HTTP POST抛出订户异常

注射服务

@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({ 
    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')); 
    } 
} 

当视图被呈现和方法onSubmit被调用,我得到以下错误:

Error when "onSubmit" method is called

有关错误的任何信息,将不胜感激。

回答

0

的解决方案是改变返回CompanyService类的test()方法的数据类型:

注射服务

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')); 
} 

元器件

我删除3参数,因为Observable<any>只允许2个参数:成功功能和错误功能

public onSubmit():void{ 
    this.companyServ.test().subscribe(data => { 
     console.log('Data', data); 
    }, err => { 
     console.error('Error', err); 
    }); 
}