【问题标题】:Uncaught TypeError: this.jsonp.request is not a function in Angular2未捕获的类型错误:this.jsonp.request 不是 Angular2 中的函数
【发布时间】:2016-08-09 14:02:17
【问题描述】:

我收到以下错误。 未捕获的 TypeError:this.jsonp.request 不是 Angular2 中的函数。谁能帮我解决这个问题。

我的代码会是这样的:

  1. RequestService.ts

    import {Component} from '@angular/core';
    import {JSONP_PROVIDERS, Jsonp,RequestMethod, RequestOptions, URLSearchParams,JSONP_BINDINGS, BaseRequestOptions} from '@angular/http';
    import {Injectable} from '@angular/core';  
    import 'rxjs/add/operator/map';
    
    @Injectable()
    
    @Component({
       providers: [JSONP_PROVIDERS]
    })
    
    export class RequestService {    
      constructor(public jsonp?:Jsonp) {
         this.jsonp = Jsonp;
      }
    
    getValues = (url) => {
     let  _urlParams = new URLSearchParams();
     _urlParams.set('contentType', 'application/jsonp; charset=utf-8');
     _urlParams.set('dataType', 'jsonp');
     _urlParams.set('timeout', '5000');       
    
     this.jsonp.request(url + "&callback=JSONP_CALLBACK", {       // getting error here
        contentType: "application/jsonp; charset=utf-8",
        dataType: 'jsonp',
        timeout: 5000
     })
        .map(res => {                 
             return res.json();
         })
         .subscribe(res => {
             // here some stuffs with response
         }), err => {
         console.log('error')
     };
    
    }
    }
    
  2. abc.ts

    import {RequestService}           from './../request_service';
    
    export class ABC {
      private request:any = new RequestService();
    
      bindValues() {
         this.request.getValues('http://google.co.in');    // note: url given here is sample
          }
       }
    

提前致谢

【问题讨论】:

  • 你用的是哪个版本的Angular2?
  • Angular 版本 2.0.0-rc.1 @Thierry Templier

标签: angular angular2-services


【解决方案1】:

问题出在这一行:

constructor(public jsonp?:Jsonp) {
  this.jsonp = Jsonp; // <----
}

使用 public 或 private 关键字,您不需要设置属性。此外,您设置了类而不是构造函数参数...

尝试以下方法:

constructor(public jsonp?:Jsonp) {
}

编辑

我认为你的装饰器有问题。在服务的情况下,您只需要 @Injectable 一个,而不是 @Component 一个(仅适用于组件)。

所以我会使用以下内容:

@Injectable()
export class RequestService {    
  constructor(public jsonp?:Jsonp) {
  }

  (...)
}

在引导您的应用程序时设置提供程序:

bootstrap(AppComponent, [ JSONP_PROVIDERS ]);

看到这个问题:

要了解如何将依赖项注入服务,您可以查看描述分层注入器如何工作的问题:

【讨论】:

  • 感谢您的回复.. 但它没有工作。我仍然遇到同样的错误。我试图将 jsonp 对象设置为这样的类属性:export class RequestService { private jsonobj:any; constructor(public jsonp?:Jsonp) { this.jsonobj = Jsonp; } }
  • 我也试过这个 `constructor(public jsonp?:Jsonp){}' 在这种情况下 jsonp 是未定义的。即使在构造函数中分配了 jsonp。
  • 不客气!我认为这是您在服务中使用的装饰器的问题......我更新了我的答案;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-06
  • 2019-05-24
  • 2021-12-15
  • 2019-10-26
  • 2016-06-27
  • 2021-12-19
相关资源
最近更新 更多