Call Apex Using Imperative Method
Things to remember before you call apex method with imperative in LWC.
Let's check the below example component to understand more.
callApexUsingImperativeMethod.html
[<template><lightning-card title="Call apex method using imperative way" icon-name="standard:account"><div class="slds-m-around_medium"><div class="slds-border_bottom">Calling apex method Imperatively</div><template if:true={accounts}><ol class="slds-list_ordered"><template for:each={accounts} for:item="acc"><li key={acc.Id}>{acc.Name}</li></template></ol></template><lightning-button label="Show All Accounts" variant="brand" onclick={handleGetAccounts}></lightning-button><br/><br/><div class="slds-border_bottom">Calling apex method imperative with params</div><p>Annual Revenue: {revenue}</p><lightning-button label="Show revenue" variant="brand" onclick={handleRevenue}></lightning-button></div></lightning-card></template>]
callApexUsingImperativeMethod.js
[import { LightningElement, api, track } from 'lwc';import accountDetails from '@salesforce/apex/LWC_Util.accountDetails';import getAllAccounts from '@salesforce/apex/LWC_Util.getAllAccounts';export default class CallApexUsingImperativeMethod extends LightningElement {@api recordId;accounts;revenue;error;// Simple way of calling, without parametershandleGetAccounts(){getAllAccounts().then((data) =>{this.accounts = data;this.error = undefined;}).catch((error) =>{this.accounts = undefined;this.error = error;})}// Imperative calling with parametershandleRevenue(){accountDetails({accountId: this.recordId}).then((data) =>{this.revenue = data.AnnualRevenue;this.error = undefined;}).catch((error)=>{this.revenue = undefined;this.error = error;});}}]
callApexUsingImperativeMethod.js-meta.xml
[<?xml version="1.0" encoding="UTF-8"?><LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"><apiVersion>48.0</apiVersion><isExposed>true</isExposed><targets><target>lightning__AppPage</target><target>lightning__RecordPage</target></targets></LightningComponentBundle>]
LWC_Util Apex controller:
[public with sharing class LWC_Util {@AuraEnabled(cacheable=true)public static List<Account> getAllAccounts (){return [SELECT Id, Name, AccountNumber, Phone, Industry, TypeFROM Account];}@AuraEnabled(cacheable=true)public static Account accountDetails (String accountId){return [SELECT Id, Name, AccountNumber, Phone, Industry, Type, AnnualRevenueFROM AccountWHERE Id=:accountId];}}]
also find above code in SWDC World git repo.
COMMENTS