Forum Discussion

LadislavStupak's avatar
LadislavStupak
Brass Contributor
Jan 06, 2021
Solved

SPFx - Get all site collections

Dear Ladies and Gentlemen,   how can I get all site collections, for which the logged in user has access rights, through SharePoint Framework, which works in Office 365 and in SharePoint on premise...
  • LadislavStupak's avatar
    LadislavStupak
    Jan 08, 2021

    This method is working well:

     

    public GetAllSiteCollections5(context: WebPartContext😞 Promise<ISiteCollection[]> {
            
            let restApiUrl: string = context.pageContext.web.absoluteUrl + "/_api/search/query?querytext='contentclass:sts_site'";

            let siteCollections: ISiteCollection[] = [];

            let config: SPHttpClientConfiguration = new SPHttpClientConfiguration({
                defaultODataVersion: ODataVersion.v3
            });

            return new Promise<ISiteCollection[]>(async(resolve, reject) => {

                context.spHttpClient
                .get(restApiUrl, config, {headers: { Accept: "application/json;odata=minimalmetadata;charset=utf-8"}})
                .then((response: SPHttpClientResponse) => {

                    console.log("response contains: " + JSON.stringify(response));

                    response.json().then((results: any) => {

                        console.log(restApiUrl);
                        console.log("results contains: " + JSON.stringify(results));
                        
                        let resultsList = results.PrimaryQueryResult.RelevantResults.Table.Rows;
                        
                        console.log(resultsList);
                        
                        resultsList.map((result: any) => {

                            console.log(result);

                            let cell3 = result.Cells[3];
                            console.log("cell3: " + JSON.stringify(cell3));

                            let cell6 = result.Cells[6];
                            console.log("cell6: " + JSON.stringify(cell6));

                            let cell3Value = cell3.Value;
                            console.log(cell3Value);

                            let cell6Value = cell6.Value;
                            console.log(cell6Value);

                            siteCollections.push({
                                Title: cell3Value,
                                SPSiteUrl: cell6Value,
                            });
                        });

                        console.log(siteCollections);
                        resolve(siteCollections);
                    });
                }, (error: any😞 void => {

                    reject("error occured " + error);
                });
            })
        }

Resources