我目前正在将离子v1应用程序更新为离子v2,但我在基于承诺的服务方面遇到了麻烦。
IIf ( [Type] IN ('China', 'Europe', 'Hong Kong', 'India', 'Japan', 'Mexico'), 'Foreign', [Type])
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);
};
});
这很好用。
现在使用v2。
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;
}
};
});
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
});
}
}
使用v1,正确返回promise。 随着v2我得到一个错误: 此行[{1}}
的take-photos.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);
});
}
}
我不明白为什么我跟着angular tutorial about services and promises
如果有人有想法,那将非常有帮助。
答案 0 :(得分:6)
您错过了从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);
});
}