我需要使用类型脚本在Ionic2 Angular2中实例化类以提出HTTP请求



我创建了一个基本的Ionic2选项卡式项目添加了以下代码,以期调用HTTP服务。

当我尝试创建HTTP对象并将其传递到构造函数时,我会在第57行上遇到此错误。var atest = new mytesta(new Http());

app.component.ts,行:57提供的参数与呼叫目标的任何签名不匹配。

l56:atest.getTest();

这是代码

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { TabsPage } from '../pages/tabs/tabs';
import { MyTest } from '../pages/tabs/mytestfile';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
  templateUrl: 'app.html'
})

export class MyApp {
  rootPage = TabsPage;
  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
}
class MyTestA {
    constructor(public http: Http) { 
    }
  getContent(url, token)
  {
      var headers = new Headers();
        headers.append('X-ZUMO-AUTH', token);
        var response = this.http.get(url, {headers: headers}).map(res => res.json());
        console.log("response: " + response);
        return response;
  }
  getTest()
  {
       console.log("test == Works: ");
  }
}
console.log("creating a new Class")
var atest = new MyTestA(new Http());
atest.getTest();

您不能像新的HTTP();它具有太多的依赖性。您可以使用服务来使用HTTP并将其注入组件或直接注入HTTP。在您的组件中,将您的服务注入构造函数。(我希望不要将两个类都放在同一文件组件中,只能在单独的文件中创建一个类别,然后使用@injectable()。

https://blog.thoughtram.io/angular/2015/09/17/resolve-service-service-depperencies-in-angular-2.html

 export class MyApp {   
  rootPage = TabsPage;
   constructor(platform: Platform, private service: MyTestA) {
    service.getTest(); // notice here
    platform.ready().then(() => {
     StatusBar.styleDefault();
     Splashscreen.hide();
    });
   }
}

i将课程注射为服务,并在构造函数内部称为方法

相关内容

  • 没有找到相关文章

最新更新