打字无法在Ionic 2 App中找到提供商

时间:2016-11-02 03:54:16

标签: angular ionic2 pouchdb typescript-typings

我已经创建了一个初始化PouchDB数据库的服务,并试图在我的另一个组件中调用该服务及其方法。我一直收到这个错误:

    [23:43:34]  Error: Error at /Users/Brad/IonicApps/CMTAv2/.tmp/pages/projects/projects.ts:24:27 
[23:43:34]  Cannot find name 'ProjectService'. 
[23:43:34]  ngc failed 
[23:43:34]  ionic-app-script task: "build" 
[23:43:34]  Error: Error 

以下是我的服务代码:

    import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

/*
  Generated class for the ProjectService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/

let PouchDB = require('pouchdb');

@Injectable()
export class ProjectService {
  private _db;
  private _projects;

  constructor(public http: Http) {
    console.log('Hello ProjectService Provider');
  }

  initDB() {
    this._db = new PouchDB('Projects', { adapter: 'websql' });
  }

  add(project) {
    return this._db.post(project);
  }

  delete(project) {
    return this._db.remove(project);
  }

  getAll() {

    if (!this._projects) {
      return this._db.allDocs({ include_docs: true})
          .then(docs => {

            // Each row has a .doc object and we just want to send an
            // array of birthday objects back to the calling controller,
            // so let's map the array to contain just the .doc objects.

            this._projects = docs.rows.map(row => {
              // Dates are not automatically converted from a string.
              row.doc.Date = new Date(row.doc.Date);
              return row.doc;
            });

            // Listen for changes on the database.
            this._db.changes({ live: true, since: 'now', include_docs: true})
                .on('change', this.onDatabaseChange);

            return this._projects;
          });
    } else {
      // Return cached data as a promise
      return this._projects;
    }
  }

  private onDatabaseChange = (change) => {
    var index = this.findIndex(this._projects, change.id);
    var project = this._projects[index];

    if (change.deleted) {
      if (project) {
        this._projects.splice(index, 1); // delete
      }
    } else {
      change.doc.Date = new Date(change.doc.Date);
      if (project && project._id === change.id) {
        this._projects[index] = change.doc; // update
      } else {
        this._projects.splice(index, 0, change.doc) // insert
      }
    }
  }

  // Binary search, the array is by default sorted by _id.
  private findIndex(array, id) {
    var low = 0, high = array.length, mid;
    while (low < high) {
      mid = (low + high) >>> 1;
      array[mid]._id < id ? low = mid + 1 : high = mid
    }
    return low;
  }


}

这是我的另一个组件的代码:

    import {Component, NgZone} from '@angular/core';
import {NavController, ModalController} from 'ionic-angular';
import { ReportsPage } from '../reports/reports';
import { ProjectDetailPage } from '../project-detail/project-detail';
import { ProjectService } from  '../../providers/project-service.ts';
import { Platform } from 'ionic-angular';

/*
  Generated class for the Projects page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/



@Component({
  selector: 'page-projects',
  templateUrl: 'projects.html',
  providers: [ProjectService]
})
export class ProjectsPage {
  public projects = [];
  private projectService: ProjectService;

  constructor(public navCtrl: NavController,
              public modalCtrl: ModalController,
              private platform: Platform,
              private zone: NgZone) {

    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.
      this.projectService.initDB();
      this.projectService.getAll()
          .then(data => {
            this.zone.run(() => {
              this.projects = data;
            });
          })
          .catch(console.error.bind(console));
    });

  }

  ionViewDidLoad() {
    console.log('Hello Projects Page');

  }

  public addProject() {
    let modal = this.modalCtrl.create(ProjectDetailPage);
    modal.present();
  }

  public openProject(project) {
    this.navCtrl.push(ReportsPage);
  }

}

出现这种情况的原因是什么?我试过搞乱app.module.ts中的声明,但是没有做任何事情。我的IDE告诉我它可以找到'ProjectService',所以那里没有问题。我是否必须在Typings配置中声明提供程序?

提前感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

因为你没有实例化服务。

export class ProjectsPage {
  public projects = [];
  private projectService: ProjectService;

  constructor(public navCtrl: NavController,
              public modalCtrl: ModalController,
              private platform: Platform,
              private zone: NgZone) {

您只是说有一个带有ProjectService类型的对象projectService,但您没有创建它。您可以将其移动到构造函数参数:

export class ProjectsPage {
  public projects = [];

  constructor(public navCtrl: NavController,
              public modalCtrl: ModalController,
              private projectService: ProjectService;
              private platform: Platform,
              private zone: NgZone) {

或在构造函数内部:

this.projectService = new ProjectService(this.http); <-- Need to add http to your constructor arguments.

第一个选项是最好的选项,只有在实例化服务之前等待条件发生时才应使用第二个选项。

答案 1 :(得分:1)

@Component({
  selector: 'page-projects',
  templateUrl: 'projects.html',
  providers: [ProjectService]
})
  

不要在组件内使用提供程序。从组件中删除Provider并仅在app.module.ts中添加

答案 2 :(得分:1)

  

我的IDE告诉我它可以找到'ProjectService',所以有   那不是问题。我是否必须在打字中声明提供者   配置还是什么?

假设导入中使用的路径是正确的,请尝试从导入句子中删除.ts

import { ProjectService } from  '../../providers/project-service.ts';

应该只是

import { ProjectService } from  '../../providers/project-service';

就像@Aravind所说,不要使用providers内部组件;请改用NgModule中的一个:

@NgModule({
  declarations: [
    MyApp,

    // Pages
    Page1,
    Page2,

    // Pipes
    MyCustomPipe,

    // Directives
    MyCustomDirective,
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,

    // Pages
    Page1,
    Page2
  ],
  providers: [ ProjectService, ... ] // <- here!
})
export class AppModule {}

答案 3 :(得分:1)

我遇到了问题。导入文件的路径错误!所以检查一下你的情况是否正确。