首页 文章

“TypeError:无法读取未定义的属性'then'

提问于
浏览
4

我目前正在将我的离子v1应用程序更新为离子v2,但我在基于承诺的服务方面遇到了麻烦 .

离子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 .

离子v2

take-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 在take-photos.ts中为此行 this.cameraService.getPicture().then

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

如果有人有想法,那将是非常有帮助的 .

1 回答

  • 5

    您错过了从 getPicture 函数返回承诺,因此您可以使用 .then 函数 .

    Code

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

相关问题