Replies: 4 comments 2 replies
-
It works fine on angular 15, I think the documentation is just outdated and Ability is not needed anymore. Just remove any occurrence of In app.module, instead of import { NgModule } from '@angular/core';
import { AbilityModule } from '@casl/angular';
import { PureAbility, createMongoAbility } from '@casl/ability';
@NgModule({
imports: [
// other modules
AbilityModule
],
providers: [
{ provide: Ability, useValue: createMongoAbility() },
]
// other properties
})
export class AppModule {} (Ability is not needed anymore, the docs seem a bit outdated IMHO) Also instead of using @Injectable({ provideIn: 'root' })
export class Session {
constructor(
// use default PureAbility (without typing help)
// private readonly ability: PureAbility,
// or if you have a custom ability type, for better typesafity
@Inject(PureAbility)
private readonly ability: AppAbility
) {}
private updateAbility(user): void {
// default
// const { can, rules } = new AbilityBuilder(createMongoAbility);
// or type based
const { can, rules } = new AbilityBuilder<AppAbility>(createMongoAbility);
if (user.role === 'admin') {
can('manage', 'all');
} else {
can('read', 'all');
}
this.ability.update(rules);
}
} Full example https://stackblitz.com/edit/angular-mbdvmu?file=src/main.ts (NOTE: I'm relatively new to this library) |
Beta Was this translation helpful? Give feedback.
-
@TheDelta is right! Thank you for helping to explain this. Ability is deprecated because its main purpose can be translated to factory function. In the next major version I plan to rename PureAbility to Ability. This is explained in jsdoc deprecation description which you should see in your IDE |
Beta Was this translation helpful? Give feedback.
-
thank you for your reply.
|
Beta Was this translation helpful? Give feedback.
-
solution: import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { AbilityModule } from '@casl/angular';
import { AbilityBuilder, createMongoAbility, PureAbility } from '@casl/ability';
@Component({
selector: 'my-app',
standalone: true,
imports: [CommonModule, AbilityModule],
providers: [{ provide: PureAbility, useValue: createMongoAbility() }],
template: `
<div *ngIf="'read' | able: 'Article'">
read Article ok
</div>
`,
})
export class App {
constructor(private ability: PureAbility) {
const { can, rules, build } = new AbilityBuilder(PureAbility);
const abilityConf = new PureAbility<['read' | 'update', 'Article']>([
{ action: 'read', subject: 'Article' },
{ action: 'update', subject: 'Article' },
]);
this.ability.update(abilityConf.rules);
console.log('📢 [update Article ?]', ability.can('update', 'Article'));
}
}
bootstrapApplication(App); |
Beta Was this translation helpful? Give feedback.
-
on angular 15, Ability is deprecated
will there be a version 15?
Beta Was this translation helpful? Give feedback.
All reactions