Using the Sitecore context

Version: 9.0

You can configure an Angular application to use the Sitecore context, using the SciContextService service of SPEAK 3. The context is an object that contains information about the user, culture, language settings, and database settings. You use the context, for example, to show the username or to set the language.

The following is an example of a Context object:

RequestResponse
{
  ContentDatabase: {
    Name: string  // 'master'
  }
  Culture: {
    Name: string, // 'da-DK'
    ThreeLetterISOLanguageName: string, // 'dan'
    TwoLetterISOLanguageName: string  // 'da'
  }
  Database: {
    Name: string  // 'core'
  }
  Language: {
    Name: string  // 'da'
  }
  User: {
    LocalName: string, // 'admin'
    Name: string, // 'sitecore\admin'
    Profile: {
      FullName: string, // 'Administrator' (Another example could be 'John Doe')
      Portrait: string  // 'office/16x16/default_user.png'
    }
  }
}

Configuration and usage

The following setup makes the Context object available to the SPEAK 3 components.

Components such as the AccountInformation control use the Context object if it is configured for ng-bcl. It saves a lot of manual configuration and wiring if you give a Context object to the ng-bcl Module.

In app.module.ts:

RequestResponse
import { SciContextModule, SciContextService, sciContextFactory } from '@speak/ng-sc/context';
import { CONTEXT } from '@speak/ng-bcl/core/context';
...
imports: [ 
  SciContextModule 
],
providers: [
  { provide: CONTEXT, useFactory: sciContextFactory, deps:[SciContextService] },
]
...

You must inject the Context object in a component (for example: context-example.component.ts):

RequestResponse
import { Context } from '@speak/ng-sc/context';
import { CONTEXT } from '@speak/ng-bcl';
@Component({
  selector: 'app-context-example',
  template: `
    <!-- Render the Language name -->
    <p>Language.Name: {{ ctx.Language.Name }}</p>
  `
})
export class ContextExampleComponent implements OnInit {
  ctx: Context = {} as Context;
  constructor(
    @Inject(CONTEXT) public context$: Observable<Context>
  ) {}
  ngOnInit() {
    this.context$.subscribe(context => this.ctx = context);
  }
}

The Angular documentation has more information about dependency injection tokens.

Do you have some feedback for us?

If you have suggestions for improving this article,