How to get Object Name using RecordId

0
2550
<aura:component controller="UtilityController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <!-- Attributes -->
    <aura:attribute name="sObjectName" type="String" />
    <!-- Handlers -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
		
    <div class="slds-text-body_small slds-text-color_error">Current Object Name:{!v.sObjectName}</div>
</aura:component>
({
    doInit : function(component, event, helper) {  
        var action = component.get("c.getObjectTypeName");
        action.setParams({
            recordId: component.get("v.recordId")           
        });
        action.setCallback(this, function(response) {            
            var state = response.getState();
            if (state === response.getState()) {
                component.set("v.sObjectName",response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})
public class UtilityController {
    @AuraEnabled
    public static String getObjectTypeName(String recordId){
        //Converting a string type to Salesforce ID.
        Id currentRecordId = Id.valueOf(recordId);
        //Storing the Object in variable and returning.
        String ObjectName = currentRecordId.getSObjectType().getDescribe().getName();
        return ObjectName;
    }
}

Here is the Output on the Opportunity Record: