"TypeError: cannot read property 'then' from undefined

I am currently updating my ionic v1 application for ionic v2, but I have problems based on promises.

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

It works well.

Now with v2.

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

With v1, the promise is back. With v2 I got an error: TypeError: Cannot read property 'then' of undefinedin take-photos.ts for this linethis.cameraService.getPicture().then

I do not understand why, since I followed the angular tutorial about services and promises

If anyone has an idea, this will be very helpful.

+4
source share
1 answer

, 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);
    });
}
+5

All Articles