Just starting a new project in Angular 5, coming from Angularjs, and I can't get my head around the resolve mechanism.
With Angular 1.x and ui-router, I could just really easily resolve data before my route was loaded this way :
(function () {
"use strict";
angular.module('myModule').config(function ($stateProvider) {
$stateProvider.state('myState', {
url: "/",
views: {
'main@': {
templateUrl: "/src/modules/template.part.html",
controller: "MyController",
resolve: {
something: function(ServiceA) {
return ServiceA.getSomething();
},
somethingElse: function (ServiceB, something) {
return ServiceB.getSomethingElse(something);
},
otherThing: function (ServiceC) {
return ServiceC.getOtherThing();
}
}
}
}
});
});
})();
And that was it, I could inject something
and somethingElse
in MyController
.
Now with Angular 5, if I understood correctly, this is what I have to do for the same result :
// skipping imports
@Injectable()
class ResolveA implements Resolve<any> {
constructor(private myServicA: MyService) {}
resolve() {
return this.myServiceA.getSomething()
}
}
@Injectable()
class ResolveB implements Resolve<any> {
constructor(private myServiceB: MyService) {}
resolve() {
return this.myServiceB.getSomethingElse()
}
}
@Injectable()
class ResolveC implements Resolve<any> {
constructor(private myServiceC: MyService) {}
resolve() {
return this.myServiceC.getOther()
}
}
const routes: Routes = [
{
path: '',
component: TestComponent,
resolve: {
dataA: ResolveA,
dataB: ResolveB,
dataC: ResolveC
}
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [
MyService,
ResolveA,
ResolveB,
ResolveC
]
})
export class TestRoutingModule { }
I must have missed something because this really seems like a LOT of code for just 3 return
's. Is there no possibility at all to declare an inline function or something in the resolve
part of my route ? Anywhere I look I can't find an answer to that question, I only see easy tutos and demos, but what about a big app with 5-10 resolves coming from different services ?
Or maybe I should do it in the ngOnInit
function of my component ? But it doesn't feel right either...
This is more of a "good practice" question before I start working on a big project, I just want to be sure I'm doing things right. I've manage to remove some code by doing a forkJoin
on all my observables inside a single resolver but again, this doesn't feel quite right.