如何处理AngularJs中的回调函数?

时间:2014-12-08 09:12:54

标签: javascript angularjs ionic-framework cordova-plugins

在控制器中,我从工厂返回物体。该方法是回调类型。

但问题是对象没有退缩。

我的实施如下:

.factory('fileReadFactory', ['$http',
    function ($http) {

        var objRead = {
            setReadObject: '',
            setPath: 'comMyTaxi',
            setFileName: '',
            status: false,
            errorCode: ''
        };
        var factory = {};
        factory.fileRead = function RequestFileSystem(fileName) {

            alert('factory start');
            objRead.setFileName = fileName;


            try {
                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, createDirectory, fail);
                objRead.status = true;
                return objRead;
            } catch (e) {
                return objRead;
            }
        }
        ///write steps starts
        function createDirectory(fs) {
            fs.root.getDirectory(objRead.setPath, {create: true, exclusive: false}, onSuccessCreateFile, fail);
        }

        function onSuccessCreateFile(dirEntry) {
            dirEntry.getFile(objRead.setFileName + '.txt.gz', null, gotFileEntryRead, fail);
        }

        function gotFileEntryRead(fileEntry) {
            //  alert('in 2 type step2');
            fileEntry.file(gotFileReading, fail);
        }

        function gotFileReading(file) {
            //  alert('in 2 type step3');
            readFile(file);
        }

        function readFile(file) {
            // alert('in 2 type step4');
            var reader = new FileReader();
            reader.onloadend = function (e) {
                //   alert("Text is: "+this.result);
                objRead.setReadObject = this.result;

            }
            reader.readAsText(file);
            //  alert('reading Ends');
        }

        //write file ends

        function fail(err) {
            alert('error ' + err.code);
            objRead.errorCode = err.code;
            throw e;
        }
        return factory;
    }]);

我在控制器内的呼叫就像

var objReturn = fileReadFactory.fileRead('myProfile');
    alert(objReturn.status);
    alert(JSON.parse(objReturn.setReadObject));
    if(objReturn.status){
        var obj=  JSON.parse(objReturn.setReadObject);

       // alert(obj);
      //  alert('Inside Object World');
        $scope.myprofile = obj;
    }

我没有得到if块。那么我如何管理回电;

1 个答案:

答案 0 :(得分:0)

尝试调用您的服务并在then()函数中执行警报。您还应该阅读承诺:http://andyshora.com/promises-angularjs-explained-as-cartoon.html

var objReturn = fileReadFactory.fileRead('myProfile').then(function(){
    alert(objReturn.status);
    alert(JSON.parse(objReturn.setReadObject));
    if(objReturn.status){
        var obj=  JSON.parse(objReturn.setReadObject);

       // alert(obj);
      //  alert('Inside Object World');
        $scope.myprofile = obj;
    }
});