Bare Minimum Markup For Loading Sharepoint Context In Angular Spa

Why SharePoint Context Matters

Retrieving the SharePoint context in an Angular single page application (SPA) is crucial for enabling seamless interaction with the SharePoint platform. The context contains essential information like the current user and web properties that unlock functionality for building robust SharePoint-integrated components.

  • Enables access to SharePoint REST APIs – The context provides the site URL and route base required for making requests to the broad SharePoint REST API surface area. This allows retrieving list data, user profiles, performing searches, and more.
  • Allows retrieval of current user and web properties – User login name, ID, and other properties are available in the context for displaying personalized information. Details like the current web’s title, description, and more can also be accessed.
  • Necessary for building SharePoint-aware apps – By exposing user and site information, the SharePoint context facilitates apps that can adapt based on who is logged in and where they are accessing the app from.

Minimal Setup for Loading Context

Loading the SharePoint context into an Angular SPA requires a few key steps for the initial plumbing:

  • Install and configure SPHttpClient package – The SPHttpClient module contains a custom HttpClient for communicating with SharePoint. It handles authentication and other complexities behind the scenes.
  • Create HttpClient service – A reusable service wraps the SPHttpClient for retrieving the context. This service can be injected across the app.
  • Make async call to SharePoint site URL – An async method initiates the SPHttpClient request by supplying the absolute URL of the target SharePoint site.
  • Access returned context objects – Once loaded, the context provides access to the current web and user objects for consumption.

Example Context Loading Service

Here is an example Angular service for loading the SharePoint context:

// Import HttpClient and SpHttpClient from Angular 
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { SpHttpClient, ISPHttpClientOptions } from '@microsoft/sp-http';

@Injectable({
  providedIn: 'root'
})
export class SpContextService {

  // Inject dependencies 
  constructor(
    private http: HttpClient,
    private spHttpClient: SpHttpClient
  ) {}

  // Define async method to retrieve context
  public async getContext(): Promise {

    // Build absolute URL from window location 
    const url = `${window.location.protocol}//${window.location.hostname}${window.location.pathname}`;
    
    // Get context from SharePoint 
    const context = await spHttpClient
      .get(url, SpHttpClient.configurations.v1)
      .then(response => response.json());

    // Return context object back 
    return context;
  }

}

Key aspects include:

  • Importing HttpClient and SpHttpClient modules
  • Injecting dependencies into the service
  • Constructing the absolute site URL
  • Calling the SharePoint-aware HttpClient get method
  • Returning parsed JSON response

This centralizes context retrieval in a reusable service.

Using the Context Service

Consuming the context service inside components is straightforward:

// Import SpContextService  
import { SpContextService } from './sp-context.service';

@Component({
  // metadata
})
export class MyComponent implements OnInit {

  context: any;

  constructor(private contextService: SpContextService) {}

  ngOnInit() {
  
    // Call service on init
    this.contextService.getContext()
      .then(ctx => {
        this.context = ctx;

        // Access user and web properties
        console.log(this.context.user.loginName); 
        console.log(this.context.web.title);
      });

  }

}

Usage involves:

  • Injecting the SpContextService
  • Calling getContext and awaiting the response
  • Assigning the returned context object
  • Accessing user and web properties

This makes user and site information available within components.

Next Steps After Loading Context

Once the SharePoint context is loaded into an Angular SPA, components gain access to powerful capabilities:

  • Query and display user information – User profile data can be retrieved via the user object for personalization.
  • Retrieve and show site properties – Metadata like the site name, description, templates, etc can be accessed and rendered.
  • Call other SharePoint REST endpoints – The full SharePoint REST API surface area opens up for getting content types, list data, performing search queries, and more.

In summary, loading context is a vital first step in building Angular solutions aware of their hosting SharePoint environment. The user and site details enable dynamically tailoring experiences around the current user and location in SharePoint.

Leave a Reply

Your email address will not be published. Required fields are marked *