Skip to content

Commit d042f6d

Browse files
Luuk PetersLuuk Peters
authored andcommitted
Add examples for consuming contexts in services with notification handling
1 parent 6dd1207 commit d042f6d

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

16/umbraco-cms/customizing/foundation/context-api/consume-a-context.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,17 +209,45 @@ Not all code that needs contexts lives in UI elements (web components). Services
209209
For these non-UI classes, extend `UmbControllerBase` to gain the same context consumption capabilities as elements. This base class provides `getContext()` and `consumeContext()` methods, allowing any class with a controller host to access the Context API.
210210
211211
### Get as one-time reference
212+
This example creates an example service that can show a notification in the backoffice of Umbraco based on the given text.
212213
214+
```javascript
215+
import { UmbControllerBase } from '@umbraco-cms/backoffice/class-api';
216+
import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification';
213217

218+
//The example element extends the UmbLitElement (which is the same as UmbElementMixin(LitElement))
219+
//This gives us all the helpers we need to get or consume contexts
220+
export default class ExampleService extends UmbControllerBase {
221+
async ShowNotification(notificationText) {
222+
223+
//We try to get an instance of the context
224+
const notificationContext = await this.getContext(UMB_NOTIFICATION_CONTEXT);
225+
if (!notificationContext) {
226+
throw new Error('Notification context not found!');
227+
}
228+
229+
notificationContext?.peek("positive", {
230+
data: {
231+
headline: "Success",
232+
message: notificationText
233+
}
234+
});
235+
236+
//The notification is sent, now forget the context
237+
}
238+
}
239+
```
214240
215241
### Get as a subscription
242+
This example consumes the document workspace context and saves it to a variable to be used later.
243+
216244
```javascript
217245
import { UmbControllerBase } from '@umbraco-cms/backoffice/class-api';
218246
import { UMB_DOCUMENT_WORKSPACE_CONTEXT } from '@umbraco-cms/backoffice/document';
219247

220248
// This service class extends UmbControllerBase
221249
// This gives us access to getContext() and consumeContext()
222-
export class NotificationService extends UmbControllerBase {
250+
export class ExampleService extends UmbControllerBase {
223251
#workspaceContext;
224252

225253
constructor(host) {

0 commit comments

Comments
 (0)