简体   繁体   中英

How do I deal with Angular-UI-Router resolve with an unfulfilled promise?

Lets say I have a an angular ui router route set up. When I change to that state, I'm telling Angular that I want it to resolve a factory call first then load the view. But what happens when that api call is empty? I would like to inform the user that there was no results found and stay on at my original state. Not transition to another view with no data to display. What is the best way to achieve this?

The route (which works as expected so far when I know there will be a return)

'use strict';

angular.module('testApp')
.config(function ($stateProvider) {
    $stateProvider
        .state('spinnerTest', {
            url: '/spinner_test',
            templateUrl: 'app/spinnerTest/spinnerTest.html',
            controller: 'SpinnerTestCtrl',
            resolve: {

                names: function(NamesService){

                    //What happens if I return an empty array []?
                    //How do I return to the previous state?
                    NamesService.getNames();
                }
            }
        });
  });

You can simply reject promise in resolve in case of empty array:

resolve: {
     names: function(NamesService) {
         return NamesService.getNames().then(function(names) {
             return names.length == 0 ? $q.reject('no names') : names;
         });
     }
 }

This is a cross cutting concern, it is probably not unique to the Name service, but other services you are using as well.

Since you didn't post the code to the Name service (NameService service is redundant) I will assume it uses either the $http or $resource service. You can then use a $httpInterceptor that will trigger the display of a message to the user that "The selection is unavailable at this time".

You could call $state.go in your resolve, if you'd like

'use strict';

angular.module('testApp')
.config(function ($stateProvider) {
    $stateProvider
        .state('spinnerTest', {
            url: '/spinner_test',
            templateUrl: 'app/spinnerTest/spinnerTest.html',
            controller: 'SpinnerTestCtrl',
            resolve: {

                names: function(NamesService, $state){

                    //What happens if I return an empty array []?
                    //How do I return to the previous state?
                    return NamesService.getNames().then(function(names){
                      if (!names.length) {
                        return $state.go('otherState');
                      }
                      return names;
                    });
                }
            }
        });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM