Loading Sharepoint Client Side Object Model In Angular Spa

Why Load the Client Side Object Model?

The SharePoint Client Side Object Model (CSOM) allows developers to interact with SharePoint data and operations using plain JavaScript. This provides important benefits for Angular single-page applications (SPAs):

  • Enables client-side SharePoint integration without postbacks, improving performance
  • Supports CRUD (create, read, update, delete) operations on SharePoint lists and libraries
  • Works across SharePoint environments including SharePoint Online
  • Provides a consistent API across SharePoint 2013, 2016, and 2019

By loading and initializing the CSOM in an Angular SPA, we can leverage these benefits to build fast, scalable client-side solutions with SharePoint.

Getting Set Up

To configure our Angular application to use the SharePoint CSOM, we first need to install the required libraries:

npm install @microsoft/sp-core-library @microsoft/sp-lodash-subset @microsoft/sp-odata-types

This installs the core SharePoint and OData libraries used by CSOM requests. We also need to load these into our application:

import { SPHttpClient } from '@microsoft/sp-http'; 
import { SP } from '@microsoft/sp-core-library';  
import { _ } from '@microsoft/sp-lodash-subset';

With the libraries installed and imported, we now have access to the SharePoint client APIs in our Angular services and components.

Initializing the Client Context

To call CSOM, we first initialize a ClientContext object which will authenticate us to SharePoint and handle our requests:


import { Web } from "@microsoft/sp-page-context"; 

export class SpService {

  private clientContext: SP.ClientContext;

  constructor(){
    this.clientContext = new SP.ClientContext(Web().absoluteUrl);  
  } 
}

The SP.ClientContext handles authentication, connects to the specified SharePoint site, and provides the interface for querying data and interacting with lists.

Calling the Client Side Object Model

Once our client context is initialized, we can use it to interact with SharePoint. Some common operations include:

Retrieving Lists


  getLists() {

    var lists = this.clientContext.get_web().get_lists();
    
    this.clientContext.load(lists);

    this.clientContext.executeQueryAsync()
      .then(result => {
        // process retrieved lists
      })
  }

This retrieves all lists in the current site, loads the data into the context for processing, and executes the request asynchronously when .executeQueryAsync() is called.

Querying List Items


  getListItems(listTitle) {

    var list = this.clientContext.get_web().get_lists().getByTitle(listTitle);
    
    var caml = new SP.CamlQuery();
    caml.set_viewXml('...CAML query...');
    
    var items = list.getItems(caml);
    
    this.clientContext.load(items);

    this.clientContext.executeQueryAsync()
      .then(result => {
        // process retrieved items
      })
  }  

This loads a specific list, creates a CAML query to filter items, retrieves the matching items into a collection, and loads the data into the context for processing.

CRUD Operations

We can perform create, read, update and delete operations like:


  // Create new item
  var itemCreateInfo = new SP.ListItemCreationInformation();
  var newItem = list.addItem(itemCreateInfo);
  newItem.set_item('Title', 'New Item!');
  
  // Update existing item
  var item = items.getById(15);
  item.set_item('DueDate', dueDate);
  
  // Delete item 
  item.deleteObject();

  clientContext.executeQueryAsync();  

This demonstrates creating, updating based on ID, and deleting items in a SharePoint list with CSOM.

Handling Authentication

By default, our CSOM requests will authenticate using the current user’s context in SharePoint. However, in Angular apps, we typically manage authentication using Azure Active Directory and OpenID Connect:


// Import MSAL 
import { MsalService } from '@azure/msal-angular';

constructor(private msal: MsalService) {}

// Sign in with popup  
this.msal.loginPopup()
  .subscribe(token => {
    
    // Pass auth token to CSOM requests
    this.clientContext.get_web().get_lists();  
    this.clientContext.executeQueryAsync();
  });

This signs the user in via Azure AD using the MSAL library, giving us an authentication token we can apply to our CSOM calls to authorize them.

The client context will automatically pick up on this authenticated context for any future CSOM requests. We can also manually construct a SharePointOnlineCredentials object and pass into our context for more complex authentication needs.

Tips for Optimization

For best performance with SharePoint CSOM in Angular, keep these tips in mind:

  • Initialize client context once rather than construct on every request
  • Reuse loaded objects like lists and items when possible instead of re-querying
  • Lazy load data with $expand and $select to limit bandwidth
  • Use batching for bulk operations, only calling .executeQueryAsync() once
  • Implement caching and request throttling to optimize load

Following these client-side best practices helps reduce roundtrips to SharePoint and improves response times for users.

Additional Resources

For more on working with SharePoint CSOM in Angular, see these resources:

Leave a Reply

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