Microsoft cloud engineer - SharePoint, Office 365, Azure, DotNet, Angular, JavaScript.
Microsoft cloud engineer - SharePoint, Office 365, Azure, DotNet, Angular, JavaScript.

Fake data with Angular JS services

Ever wanted to simulate JSON data within your Angular app?    The code below I found handy and wanted to share.

The goal was to override a “real data” call by watching a global flag (testmode=true).   Here we have a call to SharePoint 2013’s REST user profile service overridden which returns hardcoded JSON instead.    That enables us to develop local and offline (no SharePoint) and switch to full online mode later with real data calls.  Maybe full WebAPI services aren’t online yet.   That’s OK.  Why slow down application design?   Cheers!  

shades_smile

 

Code

//namespace
var myApp = myApp || {};

//test data
myApp.testMode = true;
myApp.testuser = {
    "d": {
        "AccountName": "DOMAIN\\testuser",
        "DisplayName": "Test User",
        "Email": "test.user@company.com"
    }
};

//Angular Service
myApp.svc = function ($q, $http) {
    $http.defaults.headers.common['Accept'] = 'application/json;odata=verbose';

    //SharePoint User Profile
    this.getMe = function () {
        //fake HTTP simulated data
        //return full promise object so controller can use ".success();"
        if (myApp.testMode) {
            var fakeHttp = {
                success: function (callback) {
                    callback(myApp.testuser);
                },
                error: function (callback) {
                    callback(myApp.testuser);
                }
            };
            return fakeHttp;
        }

        //real HTTP
        return $http.get('/_api/SP.UserProfiles.PeopleManager/GetMyProperties');
    };
};

//Angular Controller
myApp.ctl = function ($scope, $svc) {
    var vm = $scope;
    vm.init = function () {
        //data call - get current user detail
        $svc.getMe().success(function (data) {
            vm.currentLogin = data.d.AccountName;
            vm.currentDomain = data.d.AccountName.split('\\')[0];
        });
    };
    vm.init();
};

//Anuglar Module
angular.module('myApp', [])
    .controller('ctl', myApp.ctl)
    .service('$svc', myApp.svc);

UPDATE – please also read this great article covering “ngMockE2E”

© Copyright 2016
@ SPJeff

Return to Top ▲Return to Top ▲