Domanda

Qualcuno potrebbe aiutarmi a capire come restituire i dati con codifica rigida nella fabbrica di AngularJS se c'è un errore che si connette alla mia API.I miei dati rigidi si trovano in un'altra fabbrica chiamata "datafactory".Apprezzo l'assistenza.

service.factory("ScheduleFactory", ['$http', '$resource', '$q', 'dataFactory', function($http, $resource, $q, dataFactory) {
        var objFactory = {};

        objFactory.getDaysOfWeek = function(includeWeekends) {
            var days = [];
            var API  = $resource(restURL + '/daysOfWeek/');

            API.query()
                .$promise
                    .then(function(data) {
                        isEmpty = (data.length === 0);

                        if (!isEmpty) {
                            days    = data;
                        };
                    })
                    .catch(function(error) {
                        console.log("rejected " + JSON.stringify(error));

                        var data    = null;
                        days    = dataFactory.daysOfWeek;

                        console.log(days.length); // returns 5
                    });


            console.log("after promise " + days.length);  // returns 'after promise 0'

            return days;
        };
.

La mia datafactory è definita come segue:

dataApp.factory("dataFactory", function() {
    objDataFactory  = {};

    objDataFactory.daysOfWeek = [
        {   dayName:        'Monday'
            , dayAbbrev:    'Mon'
            , index:        1
            , isSelected:   false
            , isWeekday:    true    }
        , { dayName:        'Tuesday'
             , dayAbbrev:   'Tue'
             , index:       2
             , isSelected:  false
             , isWeekday:   true    }
        , { dayName:        'Wednesday'
             , dayAbbrev:   'Wed'
             , index:       3
             , isSelected:  false
             , isWeekday:   true    }
        , { dayName:        'Thursday'
             , dayAbbrev:   'Thu'
             , index:       4
             , isSelected:  false
             , isWeekday:   true    }
        , { dayName:        'Friday'
             , dayAbbrev:   'Fri'
             , index:       5
             , isSelected:  false
             , isWeekday:   true    }
    ];

    return objDataFactory;
});
.

È stato utile?

Soluzione

Mi piacerebbe pensare che questo sia quello che stai cercando:

service.factory("ScheduleFactory", ['$http', '$resource', '$q', 'dataFactory', function($http, $resource, $q, dataFactory) {
     var objFactory = {};

     objFactory.getDaysOfWeek = function(includeWeekends) {
          var API  = $resource(restURL + '/daysOfWeek/'), defObj = $q.defer();

          var daysQuery = API.query();
          daysQuery.$promise.then(function(data) {
                    //you can add anything else you want inside this function
                    defObj.resolve(data);
               }, function(error) {
                    //you can add anything else you want inside this function
                    defObj.resolve(dataFactory.daysOfWeek);
               });

            return defObj.promise;
        };
.

Ho saltato qualsiasi formattazione dei dati e dettagli di assegnazione perché ti è responsabile di cambiarli comunque.Avvolgendo la tua query API in una promessa in più ottieni la possibilità di manipolare ciò che viene restituito.Se è possibile raggiungere la tua API, restituisci i dati da esso nella risoluzione della tua promessa esterna.Altrimenti, si restituisci i tuoi dati con codifica rigida dal tuo altro servizio nella risoluzione della tua promessa esterna.

Altri suggerimenti

No catch block, use a regular error callback function:

   API.query()
        .$promise
            .then(function(data) {
                    isEmpty = (data.length === 0);

                    if (!isEmpty) {
                        days    = data;
                 },
                 function(error) { // removed catch here
                    console.log("rejected " + JSON.stringify(error));

                    var data    = null;
                    days    = dataFactory.daysOfWeek;

                    console.log(days.length); // returns 5
                ...

See in the docs:

then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top