问题描述:

I'm moving to stateless components in my angular 1.x app.

I moved out all data loading from the controller code, and I'm using the ui-router's resolve functionality. As I handle every internal state change with a $state transition in the same $state, I don't want to fetch all that data from the backend, only when it's required (I need different data).

In order to acquire this behavior, I'm relying heavily on params. Example:

...

.state('myapp.child', {

url: '/child',

controller: function ($state, foo, bar) {

function someEvent() {

// Provision $stateParams to prevent fetching

$state.go($state.current, {foo: foo, bar:bar});

}

},

params: {

foo: null,

bar: null

},

resolve: {

/**

* @ngInject

*/

foo: function(fooService, $stateParams) {

if ($stateParams.foo !== null) { // <= Duplication

return foo;

} else {

return fooService.get();

}

},

/**

* @ngInject

*/

bar: function(barService, $stateParams) {

if ($stateParams.bar !== null) { // <= Duplication

return bar;

} else {

return barService.get();

}

}

}

});

My question is: Is there any way to directly tell the router to resolve those values? Or is there a nice way to avoid that null checks in the resolve block?

网友答案:

You could use ternaries and ES6 (although the ES6 is just the lambda) to clean it up a little. I added a lodash function in, but you can simply use the === check as you had:

bar: function(barService, $stateParams) =>
  return !_.isNull($stateParams.bar) ? $stateParams.bar : barService.get()
相关阅读:
Top