I'm currently updating my ionic v1 app to ionic v2 but I'm in trouble with promise based service.
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);
};
});
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;
}
};
});
This is working well.
Now with the v2.
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
});
}
}
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 the v1, the promise is correctly returned.
With the v2 I got an error :
TypeError: Cannot read property 'then' of undefined
in take-photos.ts for this line this.cameraService.getPicture().then
I do not understand why as I followed the angular tutorial about services and promises
If anyone have an idea it would be really helpful.
You missed to return promise from getPicture
function, so that you can have .then
function over it.
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With