MobileFirst JsonStore не открывается

Я использую плагин jsonStore с mfp cli.

Я подтвердил, что плагин установлен. Вызов любого другого WL. API работает в моем проекте

но когда я запускаю этот код, я получаю сообщение об ошибке:

PERSISTANT_STORE_NOT_OPEN

(function () {
'use strict';

angular
    .module('app')
    .run(appRun);

appRun.$inject = [ '$ionicPlatform', '$rootScope','MFPClientPromise', '$state', 'signinService', 'errorToastService', '$ionicHistory' ];

window.Messages = {
    // Add here your messages for the default language.
    // Generate a similar file with a language suffix containing the translated messages.
    // key1 : message1,
};

window.wlInitOptions = {
    // Options to initialize with the WL.Client object.
    // For initialization options please refer to IBM MobileFirst Platform Foundation Knowledge Center.
};

window.MFPClientDefer = angular.injector(['ng']).get('$q').defer();
window.wlCommonInit = window.MFPClientDefer.resolve;
window.MFPClientDefer.promise.then(function wlCommonInit(){
    // Common initialization code goes here or use the angular service MFPClientPromise
    console.log('MobileFirst Client SDK Initilized');
    mfpMagicPreviewSetup();
});

function appRun($ionicPlatform, $rootScope, MFPClientPromise, $state, signinService, errorToastService, $ionicHistory){
    $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
            cordova.plugins.Keyboard.disableScroll(true);

        }
        if (window.StatusBar) {
            // org.apache.cordova.statusbar required
            StatusBar.styleDefault();
        }

        //android backbutton handling
        $ionicPlatform.registerBackButtonAction(function (event) {
            event.preventDefault();
            //if ($ionicHistory.currentStateName === 'app.capture-check'){
            //    event.preventDefault();
            //} else {
            //    $ionicHistory.goBack();
            //}
        }, 100);

        MFPClientPromise.then(function(){
            WL.Logger.ctx({pkg: 'io.ionic'}).debug('mfp and ionic are ready, safe to use WL.* APIs');

            //get the devices ID
            var deviceId = WL.Device.getID({
                onSuccess: function (response) {
                    console.log('Device ID: ' + response.deviceID);
                    return response.deviceID
                },
                onFailure: function () { console.log("didn't get deviceId") }
            });

            //get the devices network info
            var networkInfo = WL.Device.getNetworkInfo(function (response) {
                console.log('network info: ' + angular.toJson(response));
                return response;
            });


            $rootScope.busyInd = new WL.BusyIndicator ({text: "Please wait..."});

            //auth challenge handler
            $rootScope.challengeHandler = WL.Client.createChallengeHandler("KMF_AuthenticatorRealm");

            $rootScope.challengeHandler.isCustomResponse = function(response) {

                console.log("Inside isCustomResponse:   ", response );

                if (!response || !response.responseJSON) {
                    return false;
                }

                if (response.responseJSON.authStatus) {

                    console.log("Inside isCustomResponse return true? :   ", response.responseJSON.authStatus );
                    return true;
                } else {
                    return false;
                }
            };

            $rootScope.challengeHandler.logger = WL.Logger.create({pkg:"challengeHandler"});

            $rootScope.challengeHandler.handleChallenge = function(challenge) {
                console.log("handle challenge in challenge handler", challenge);
                var authStatus = challenge.responseJSON.authStatus;

                var challengeUsername = signinService.username;
                var challengePassword = signinService.password;

                $rootScope.ctok = challenge.responseJSON.ctok;
                signinService.disclosure = challenge.responseJSON.disclosure;
                signinService.challenge = challenge.responseJSON.challenge;
                signinService.depositor = challenge.responseJSON.depositor;
                signinService.reviewer = challenge.responseJSON.reviewer;
                signinService.reportviewer = challenge.responseJSON.reportviewer;
                signinService.question = challenge.responseJSON.question;

                this.logger.info("handleChallenge :: authStatus :: " + authStatus);

                if (authStatus == "credentialsRequired") {

                    //if not at signin state, go there
                    if(!$state.includes('signin')){
                        $state.go('signin');
                    }

                    //jsonStore
                    var collections = {
                        forensics: {
                            searchFields: {userId: 'string'}
                        }
                    };

                    WL.JSONStore.init(collections);

                    WL.JSONStore.get('forensics').findAll()
                        .then(
                        function(reponse){
                            console.log(reponse);
                        })
                        .fail(function(error){
                            console.log(error);
                        });

                    var reqURL = '/my_custom_auth_request_url';
                    var options = {};
                    options.parameters = {
                        username : challengeUsername,
                        password : challengePassword,
                        tfaMobileToken: "",
                        serialNumber: "uniqueFromDevice0001",
                        userAgent: "KTT RDC v1.0",
                        remoteAddress: "111.222.333.444",
                        macAddress: "",
                        mobileDeviceId: "some-sort-of-GUID", // deviceId,
                        carrier:  "cricket",//networkInfo.carrierName,
                        mitekDeviceInfo: "",
                        requiredServerAction: "mlogon",
                        disclosureResult: null,
                        verifySecQuestionId: null,
                        verifySecAnswer: null
                    };
                    options.headers = {};
                    $rootScope.challengeHandler.submitLoginForm(reqURL, options, $rootScope.challengeHandler.submitLoginFormCallback);
                }
                else if (authStatus == "UserCredentialsFailed") {
                    $rootScope.busyInd.hide();
                    errorToastService.errorToast(authStatus);

                }
                else if (authStatus == "disclosureChallenge") {
                    $rootScope.busyInd.hide();
                    $ionicHistory.clearCache();
                    $ionicHistory.nextViewOptions({
                        disableBack: true
                    });
                    $state.go('terms');

                }
                else if (authStatus == "questionChallenge") {
                    $rootScope.busyInd.hide();
                    $ionicHistory.clearCache();
                    $ionicHistory.nextViewOptions({
                        disableBack: true
                    });
                    $state.go('securityQuestions');

                }
                else if (authStatus == "complete"){
                    $rootScope.busyInd.hide();
                    console.log("handle challenge in challenge handler", challenge);
                    $rootScope.challengeHandler.submitSuccess();
                }
                else if (authStatus == "UserCredentialsFailed"){
                    console.log("handle challenge in challenge handler", challenge);
                    //signinService.signout().then(function () {
                    //    $rootScope.busyInd.hide();
                    //    console.log('after signout(): ' + angular.toJson(signinService));
                    //    $state.go('signin');
                    //});
                }
            };

            $rootScope.challengeHandler.handleFailure = function(data){
                $rootScope.busyInd.hide();
                console.log("handle Failure in challenge handler", data);
                errorToastService.errorToast(data.error);
            };

            $rootScope.challengeHandler.submitLoginFormCallback = function(response) {

                console.log("submitLoginFormCallBack response:   ", response );

                var isLoginFormResponse = $rootScope.challengeHandler.isCustomResponse(response);//.responseJSON.WL-Authentication-Failure.KMF_AuthenticatorRealm);
                if (isLoginFormResponse){
                    console.log("submitLoginFormCallBack isLoginFormResponse:   " + isLoginFormResponse );
                    $rootScope.challengeHandler.handleChallenge(response);
                }
            };

        });

        //listen for state change errors
        $rootScope.$on('$stateChangeError',
            function(event, toState, toParams, fromState, fromParams, error){
                console.log('STATE CHANGE ERROR: Event:' + angular.toJson(event) + ' toState:'
                    + angular.toJson(toState) + ' toParams:' + angular.toJson(toParams) + ' fromState:'
                    + angular.toJson(fromState) + ' fromParams:' + angular.toJson(fromParams) + ' Error:' + error);
            });
    });
}

function mfpMagicPreviewSetup(){
    var platform;
    //nothing to see here :-), just some magic to make ionic work with mfp preview, similar to ionic serve --lab
    if(WL.StaticAppProps.ENVIRONMENT === 'preview'){
        //running mfp preview (MBS or browser)
        platform = WL.StaticAppProps.PREVIEW_ENVIRONMENT === 'android' ? 'android' : 'ios';
        if(location.href.indexOf('?ionicplatform='+platform) < 0){
            location.replace(location.pathname+'?ionicplatform='+platform);
        }
    }
}
}
})();

person Derek Hannah    schedule 10.02.2016    source источник
comment
Какой плагин? Это гибридное приложение или приложение Cordova?   -  person Idan Adar    schedule 10.02.2016
comment
cordova-plugin-mfp-jsonstore 7.1.0 IBM MobileFirst Platform Foundation — JSONStore   -  person Derek Hannah    schedule 10.02.2016
comment
я пробовал это в браузере, симуляторе и устройстве, та же ошибка   -  person Derek Hannah    schedule 10.02.2016
comment
Где вы размещаете этот код в своем приложении? wlCommonInit? Какой у вас номер сборки MFPF 7.1? Можете ли вы предоставить образец приложения? Что вы просматриваете — iOS? Андроид?   -  person Idan Adar    schedule 10.02.2016
comment
Я добавил весь app.js моего ионного проекта, я просматриваю на iOS   -  person Derek Hannah    schedule 10.02.2016
comment
И когда вы попробуете этот код в новом приложении Cordova для mfp без всего вашего добавленного кода, он тоже не сработает?   -  person Idan Adar    schedule 10.02.2016
comment
поэтому я только что добавил WL.JSONStore.init() в wlCommonInit и получаю эту ошибку... Ошибка: не удалось вызвать WL.JSONStore.init, поскольку JSONStore отсутствует в приложении. Добавьте JSONStore в дескриптор приложения, пересоберите и разверните его.   -  person Derek Hannah    schedule 10.02.2016
comment
Вы редактировали какую-либо папку плагина? Отметьте fetch.json для cordova-plugin-mfp-jsonstore и убедитесь, что путь существует. Проверьте файл ‹environment›.json на наличие installed_plugins, чтобы убедиться, что cordova-plugin-mfp-jsonstore есть в списке.   -  person Chevy Hungerford    schedule 10.02.2016
comment
Нет, я только добавил плагин   -  person Derek Hannah    schedule 10.02.2016
comment
Вы можете запустить mfp -v, чтобы узнать, какая версия CLI у вас работает?   -  person Chevy Hungerford    schedule 10.02.2016
comment
Можете ли вы добавить вышеуказанные проверки, которые я просил в предыдущем комментарии? 1. Проверьте папку plugins для каталога ./cordova-plugin-mfp-jsonstore 2. Внутри папки plugins проверьте fetch.json для cordova-plugin-mfp-jsonstore и убедитесь, что путь существует на вашем компьютере 3. проверьте <environment>.json для installed_plugins, чтобы убедиться, что cordova-plugin-mfp-jsonstore указан   -  person Chevy Hungerford    schedule 10.02.2016
comment
Все это проверено   -  person Derek Hannah    schedule 10.02.2016
comment
Давайте продолжим обсуждение в чате.   -  person Chevy Hungerford    schedule 11.02.2016
comment
Каковы ваши локальные настройки среды? ОС, Java версия?   -  person Chevy Hungerford    schedule 11.02.2016
comment
@DerekHannah есть новости?   -  person Idan Adar    schedule 25.02.2016


Ответы (1)


JSONStore является асинхронным

Поскольку у вас есть:

//jsonStore
var collections = {
    forensics: {
        searchFields: {userId: 'string'}
    }
};

WL.JSONStore.init(collections);

WL.JSONStore.get('forensics').findAll()
    .then(
        function(reponse){
            console.log(reponse);
    })
    .fail(function(error){
            console.log(error);
     });

Вы не можете гарантировать, что ваш JSONStore будет инициализирован до того, как вы попытаетесь выполнить findAll для объектов внутри вашего JSONStore.

person Chevy Hungerford    schedule 07.04.2016