原始异常:TypeError:不是函数

Bou*_*zza 2 angular

我需要将一个Web服务调用到一个服务文件中,以便在我的预先输入组件中使用它,但它在我的控制台中返回此问题消息

这是我的服务文件

export class DslamService {
private host = window.location.host;

constructor(private http: Http) {}

getDslams() : Observable<Site[]>  {
    return this.http.get('http://' + this.host + '/dslam_service.php')
            .map(this.extractData)
            .catch(this.handleError);
}


private extractData(res: Response) {
    let body = res.json();
    return body.data || { };
  }

  private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server     error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的先行组件:

  providers: [HTTP_PROVIDERS, DslamService],
  directives: [TYPEAHEAD_DIRECTIVES, CORE_DIRECTIVES, FORM_DIRECTIVES],
  export class TypeaheadComponent implements OnInit {
       private dslam: Site[];
       constructor(private service: DslamService) {}
       ngOnInit() { this.getDslams(); }
       getDslams() {
            this.service.getDslams()
                    .subscribe(
                     dslam => this.dslam = dslam);
       }
Run Code Online (Sandbox Code Playgroud)

在我的导航控制台中,我有这样的消息:

在此输入图像描述

小智 5

Angular2区分功能和方法.

因此,如果函数中没有参数,则它是一个angular的方法,因此必须在没有()的情况下调用getDslams.

this.service.getDslams; // this is a method call
this.service.getDslams(parameter); // this is a function call
Run Code Online (Sandbox Code Playgroud)

要使用WebService/REST,请记住,在解析对角度对象的JSON响应时,angular不会创建实现的函数.您可以访问所有属性,但不能访问任何函数/方法,直到您使用服务调用中的值自行实现对象.

希望这会有所帮助=)