Skip to content

Instantly share code, notes, and snippets.

@skysan87
Created July 5, 2021 14:32
Show Gist options
  • Save skysan87/f4a450ef534a4b22949d461a0a3fb8b4 to your computer and use it in GitHub Desktop.
Save skysan87/f4a450ef534a4b22949d461a0a3fb8b4 to your computer and use it in GitHub Desktop.
[Salesforce][Aura Component] Promiseを用いたApexアクションのコール方法
<aura:component
controller="HelloController"
implements="force:hasRecordId,force:lightningQuickAction">
<!-- 非公開属性 -->
<aura:attribute access="private" name="result" type="String" default="default value" />
<lightning:formattedText value="{! v.result }" />
<lightning:button label="Action" onclick="{! c.doAction }" />
</aura:component>
({
//参考: https://developer.salesforce.com/docs/atlas.ja-jp.lightning.meta/lightning/js_promises.htm
doAction: function(component, event, helper) {
// Apexアクションのコール
helper.callAction(component, 'c.getMessage', null)
.then(
// resolve
$A.getCallback(function(result) {
// レスポンスの値をを非公開属性に設定
component.set('v.result', result);
// モーダルを閉じる(クイックアクション)
$A.get('e.force:closeQuickAction').fire();
}),
// reject
$A.getCallback(function(error) {
console.error(error)
})
);
}
})
({
/*
* Apexアクションのコール処理
* @param {*} cmp コンポーネント
* @param {String} コールするApexのメソッド名
* @param {Object} パラメータ 例: { recordId: 'XXX'}
*/
callAction: function(cmp, apiName, param) {
return new Promise($A.getCallback(function(resolve, reject) {
const action = cmp.get(apiName);
if (param) {
// パラメータの設定
action.setParams(param);
}
// レスポンスの処理
action.setCallback(this, function(response) {
const state = response.getState();
if (state == 'SUCCESS') {
resolve(response.getReturnValue());
}
else {
reject(response.getError());
}
});
$A.enqueueAction(action);
}));
}
})
// Apex: サーバサイド
public class HelloController {
// Auraからコールされるメソッド
@AuraEnabled
public static String getMessage() {
return 'Hello World';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment