原始异常:TypeError:不是函数

时间:2016-06-15 10:11:10

标签: angular

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

这是我的服务文件

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

我的先行组件:

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

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

enter image description here

2 个答案:

答案 0 :(得分:5)

Angular2区分函数和方法。

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

this.service.getDslams; // this is a method call
this.service.getDslams(parameter); // this is a function call

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

希望这会有所帮助=)

答案 1 :(得分:0)

很少要检查

在您的服务档案中,您完成了DI?

因此...

import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Observable';

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

...

然后你通过引导服务类DslamService将DslamService添加到你的项目中吗?

...等     从&#39; ./ location / of / DslamService&#39;;

导入{DslamService}
bootstrap(AppComponent, [
  DslamService
]);

引导发生在应用程序的基础上。通常在main.ts / app.ts

最后,在构造函数的组件中,将服务更改为public并重新测试。像这样......

constructor(public service: DslamService) {}
相关问题