“TypeError:无法读取属性'然后'未定义

时间:2016-03-02 21:15:16

标签: typescript angular promise ionic2

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

离子v1

home.controller.js

IIf ( [Type] IN ('China', 'Europe', 'Hong Kong', 'India', 'Japan', 'Mexico'), 'Foreign', [Type]) 

camera.service.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);
  };
});

这很好用。

现在使用v2。

离子v2

取photos.ts

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

camera.service.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
    });
  }
}

使用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

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

1 个答案:

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