top of page
Search
  • Shreyas Dhond

Lightning Component as a Reusable Service

There are various use cases where you would want to create a service component that does a single or a set of related tasks (add logs to a salesforce object in this case) to be easily reused in other lightning components and applications.


One way to do this is firing a component event and having the service component handling it and doing the appropriate action. But this requires the component to exist in the current application context and it adds too much overhead for the event creation and handling. There is an easier way.

<aura:method> allows you to define a method as part of a component's API. We can use this to create a service component with an API that can be reused in other components or applications by just including the service component in the parent mark up. Below is a start on a logging service component that demonstrates this.


Implementation (Github)


LtngLoggerServiceCmp.cmp

<aura:component description="Logger Service Component to be used as a service in other
    components to add logging info to a common logging service"
                controller="LtngLoggerServiceController">

    <!-- Add Log API for component -->
    <aura:method name="addLog" action="{!c.addLog}">
        <aura:attribute name="logMsg" type="String"/>
        <aura:attribute name="severity" type="String"/>
        <aura:attribute name="cmpName" type="String"/>
    </aura:method>
</aura:component>

LtngLoggerServiceCmpController.js

({

    /**
     * add log method for msg, severity, and cmpName
     */
    addLog : function(component, event, helper) {
        var params = event.getParam('arguments');
        if(params) {
            helper.addLog(component, event, params.logMsg, params.severity, params.cmpName);
        }
    },
})

LtngLoggerServiceCmpHelper.js

({
    /**
     * Add log call to apex controller
     * @param {[type]} logMsg log message
     * @param {[type]} severity [Error, Info, Debug] of log
     * @param {[type]} cmpName component generating the log
     */
    addLog : function(component, event, logMsg, severity, cmpName) {
        var action = component.get("c.addLog");
        action.setParams({"logMsg" : logMsg,
            "severity" : severity,
            "cmpName" : cmpName});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {

            } else if(state === "ERROR") {
                console.log("error adding log: " + response.getError()[0].message);
            }
        });
        $A.enqueueAction(action);
    }
})

LtngLoggerServiceController.cls

public with sharing class LtngLoggerServiceController {
    @AuraEnabled
    public static void addLog(String logMsg, String severity, String cmpName) {
        //Will extend this class when logger service framework is implemented
        //for now just want to show how to use a lighting component as a service
        System.debug('LtngLoggerServiceController->logMsg: ' + logMsg + ' severity: ' + severity +
            + ' cmpName: ' + cmpName);
    }
}

Testing


TestLoggerServiceCmp.cmp

<aura:component description="Used to show and test the logger service" implements="force:appHostable">
    <!--Include service component to be used-->
    <c:LtngLoggerServiceCmp aura:id="loggerService"/>

    <lightning:button variant="destructive" label="Test Error Log" onclick="{!c.handleErrorClick}"/>
    <lightning:button variant="success" label="Test Info Log" onclick="{!c.handleInfoClick}"/>
    <lightning:button label="Test Debug Log" onclick="{!c.handleDebugClick}"/>
</aura:component>

TestLoggerServiceCmpController.js

({
    handleErrorClick : function(component, event) {
        console.log('handleErrorClick');
        component.find("loggerService").addLog("Test error log", "ERROR", "TestLoggerServiceCmp");
    },

    handleInfoClick : function(component, event) {
        console.log('handleInfoClick');
        component.find("loggerService").addLog("Test info log", "INFO", "TestLoggerServiceCmp");
    },

    handleDebugClick : function(component, event) {
        console.log('handleDebugClick');
        component.find("loggerService").addLog("Test debug log", "DEBUG", "TestLoggerServiceCmp");
    },
})


1 view0 comments

Comments


bottom of page