"TypeError: Cannot read property 'then' of undefined

"TypeError: Cannot read property 'then' of undefined

我目前正在将我的 ionic v1 应用程序更新到 ionic v2,但我在使用基于承诺的服务时遇到了麻烦。

ionic v1

home.controller.js

angular.module('myApp.home', ['myApp.services.camera',])

.controller('HomeCtrl', function($scope, CameraService) {
  $scope.getPicture = function() {
    var onSuccess = function(result) {
      // Some code
    };

    var onError = function(err) {
      // Some code
    };

    CameraService.getPicture().then(onSuccess, onError);
  };
});

camera.service.js

angular.module('myApp.services.camera', [])

.service('CameraService', function($q, $ionicPlatform, $cordovaCamera) {
  return {
    getPicture : function() {
      var deferred = $q.defer();

      var onSuccess = function(result) {
        deferred.resolve(result);
      };

      var onError = function(err) {
        deferred.reject(err);
      };

      // my options here

      $ionicPlatform.ready(function() {
        $cordovaCamera.getPicture(options).then(onSuccess, onError);
      });

      return deferred.promise;
    }
  };
});

效果很好。

现在使用 v2.

ionic v2

取-photos.ts

import {Page, NavController} from 'ionic-angular';
import {CameraService} from '../../services/camera.service';

@Page({
  templateUrl: 'build/pages/take-photos/take-photos.html',
  providers: [CameraService]
})
export class TakePhotosPage {

  constructor(private cameraService: CameraService) {}

  getPicture () {
    this.cameraService.getPicture().then((result) => {
      console.log(result); // Did not called
      // Some code
    }, (err) => {
      // Some code
    });
  }
}

camera.service.ts

import {Injectable} from 'angular2/core';
import {Platform} from 'ionic-angular';

@Injectable()
export class CameraService {
  constructor (private platform: Platform) {}

  getPicture () : any {
    // my options here

    this.platform.ready().then(() => {
      navigator.camera.getPicture((result) => {
        console.log(result); // Called
        return Promise.resolve(result);
      }, (err) => {
        return Promise.reject(err);
      }, options);
    });
  }
}

对于 v1,promise 已正确返回。 使用 v2 我得到一个错误: TypeError: Cannot read property 'then' of undefined in take-photos.ts 这一行 this.cameraService.getPicture().then

我不明白为什么我跟着 angular tutorial about services and promises

如果有人有想法,那将非常有帮助。

您错过了 return 来自 getPicture 函数的承诺,因此您可以对它使用 .then 函数。

代码

getPicture () : any {
    // my options here

    return this.platform.ready().then(() => {
      navigator.camera.getPicture((result) => {
        console.log(result); // Called
        return Promise.resolve(result);
      }, (err) => {
        return Promise.reject(err);
      }, options);
    });
}