Written by

Jayakumar Balasubramaniam

Share

  

Category

see all categories
intranet as a service

How to Read Termstore in SPFx (SharePoint Framework – Angular 4)

This article demonstrates how to read SharePoint TermStore data in SPFx application. Since we don’t have direct REST API support for this service we will be using the old JSOM method to read TermStore in SharePoint Framework webpart.

Implementation:

Though SPFx directly provides the user context without writing a single piece of code, to get access to TermStore we still need old SP.PageContext info help. Let’s get to know about loading _spPageContextInfo and Termsets altogether in all new SPFx with the help of SPComponentLoader.

The below implementation will fit for all type of JS frameworks supported by SharePoint Framework webparts.

Please follow the below steps and code snippets

Step 1:

Go to your tsconfig.json file in the SPFx webpart project and make sure to add the microsoft-ajax and sharepoint types like below

obably you already know that SPFx directly provides the user context without writing a single piece of code, to get access to termstore. However, we still need old SP.PageContext info help. Let’s get to know about loading _spPageContextInfo and Termsets altogether in brand new SPFx with the help of SPComponentLoader. It will have support for all JS frameworks supported by SharePoint Framework.section below.

      "webpack-env",

      "microsoft-ajax",

      "sharepoint"

    ],

Code Snippet: 1

Step 2:

Next step is to add the required node module packages to your project through package.json file, open the file and add the dependencies for Microsoft-ajax and sharepoint like below,

    "@types/microsoft-ajax": "0.0.33",

    "@types/mocha": ">=2.2.33 <2.6.0",

    "@types/sharepoint": "^2013.1.6",

Code Snippet: 2

Now go to your npm command prompt and make sure that the terminal is pointing to your project directory and restore the newly added angular 4 package dependencies by using the command npm install

Example: E:\your project directory >npm install

Now we have set all the dependencies to read the TermStore using SharePoint Framework and the final step is right below

Last step:

Go to the default webpart.ts file which is located in the below location \\{solutiondirectory} > src > webparts > {webpartName}\{solutionName}WebPart.ts file generated by SPFx generator where you will append your html code to the  DOM element.

          Example: E:\first-spfx-webpart\src\webparts\helloworld\helloworldWebPart.ts

Now we have to add the reference scripts to get the SP.PageContext. The scripts has to be referred in proper order because one script depends on other one.

To load the scripts we will be using SPComponentLoader.loadScript in Oninit() method of SPFx webpart, and load the JS references listed here,

  • js,
  • js,
  • Runtime.js,
  • js,
  • Taxonomy.js

Please refer the below code snippet for the same,

protected onInit(): Promise<void> {

    let siteColUrl= this.context.pageContext.site.absoluteUrl;

    SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/init.js', {

        globalExportsName: '$_global_init'

      })

        .then((): Promise<{}> => {

          return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/MicrosoftAjax.js', {

            globalExportsName: 'Sys'

          });

        })

        .then((): Promise<{}> => {

          return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/SP.Runtime.js', {

            globalExportsName: 'SP'

          });

        })

        .then((): Promise<{}> => {

          return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/SP.js', {

            globalExportsName: 'SP'

          });

        })

        .then((): Promise<{}> => {

          return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/SP.taxonomy.js', {

            globalExportsName: 'SP'

          });

        })

        .then((): void => {

            let spContext: SP.ClientContext =new SP.ClientContext(siteColUrl);

            let taxSession =  SP.Taxonomy.TaxonomySession.getTaxonomySession(spContext);

            let termStore  = taxSession.getDefaultSiteCollectionTermStore();

            let termGroups = termStore.get_groups();

            let termGroup = termGroups.getByName("People");

            let termSets = termGroup.get_termSets();

            this.loadDepartment(termSets, spContext);

          });    

  

    return super.onInit();

  }

Code Snippet: 3

Now we got the _spPageContext and TermSets in your scope, time to load specific termset please see below code snippet to load the ”Department” TermSets using spPageContext load and execute methods

private loadDepartment(termSets: SP.Taxonomy.TermSetCollection,spContext:SP.ClientContext ){

    let termSet = termSets.getByName("Department");

    let terms = termSet.getAllTerms();

    spContext.load(terms);

    spContext.executeQueryAsync(function () {

      var termsEnum = terms.getEnumerator();

      let termDepartment:any[]=[];

      while (termsEnum.moveNext()) {

        var spTerm = termsEnum.get_current();

        termDepartment.push({label:spTerm.get_name(),value:spTerm.get_name(), id:spTerm.get_id()});

      }

            window['termDepartment']= termDepartment;

      });

  }

Code Snippet: 4

The last line of the above snippet highlighted in yellow colour can be used to take your TermSet to angular 4 instances from SPFx instance and you can read this in your angular code with below code snippet,

let termDepartmentList:any[]=window['termDepartment'];

Code Snippet: 5

Summary

In this article, I discussed how to load the SharePoint TermStore (Managed Metadata) by using JSOM Page context in SharePoint Framework (SPFx) integrated with angular 4. In my next article I will explain how to add/edit the TermStore values from SPFx webparts.

If you have any questions/issues about this article, please let me know in comments.

Jayakumar Balasubramaniam

Written by Jayakumar Balasubramaniam

A technology evangelist working on Microsoft 365, SharePoint & Azure. Gets my hands dirty with latest and greatest of SharePoint, Azure & front-end frameworks. Currently working with “Hubfly – A unified digital workplace” as a Product Engineer. Getting in to the depth of the domain & technology, with my eyes for perfection, ensures that the product releases go right every time.