$provide.decorator in modern Angular
$provide.decorator has no direct equivalent because there is no $delegate. You replace the provider for a token with a subclass or a wrapper.
Before · AngularJS
app.config(function ($provide) {
$provide.decorator('UserService', function ($delegate, AuditLog) {
var originalSave = $delegate.save;
$delegate.save = function (user) {
AuditLog.record('user.save', user.id);
return originalSave.call($delegate, user);
};
return $delegate;
});
});After · Angular@Injectable()
export class AuditedUserService extends UserService {
private audit = inject(AuditLog);
override save(user: User) {
this.audit.record('user.save', user.id);
return super.save(user);
}
}
// app.config.ts
providers: [{ provide: UserService, useClass: AuditedUserService }]What changes
- { provide: UserService, useClass: AuditedUserService } swaps the implementation for everyone who injects UserService.
- The override can be scoped to a route or a component through their providers, instead of applying to the whole app.
- Decorators on built-in services map to dedicated extension points: interceptors for $http, ErrorHandler for $exceptionHandler.
Migration tip. List every decorator during the assessment. They change behavior far from the code they affect, and many only patch a third-party library that will not exist after the migration.
Related
Planning a migration or a micro-frontend platform?
In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.
Message me on LinkedIn