LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

サーバ側のアクションのコール

Posted at

何がわかる

サーバ側でデータを取得し、クライアント側で表示するまでの流れを整理する

記載のコード

クライアント側

サーバ繋ぐクラスの指定
aura:component controller="SimpleServerSideController"

cmpで扱う変数の定義
aura:attribute name="firstName" type="String" default="world"

標準コンポーネント用いてボタンの配置
lightning:button label="Call server" onclick="{!c.echo}"

cmp

<aura:component controller="SimpleServerSideController">
    <aura:attribute name="firstName" type="String" default="world"/>
    <lightning:button label="Call server" onclick="{!c.echo}"/>
</aura:component>

コントローラ

severNameをkeyとして、cmp.get("v.clientName")をvalueとする

action.setParams({ severName : cmp.get("v.clientName") });

action.setCallback() は、サーバ側のアクションが返されたら呼び出されるコールバックアクションを設定します。
action.setCallback(this, function(response)
サーバ側のアクションの結果は、コールバックの引数である response 変数に格納されます。

alert("From server: " + response.getReturnValue());
response.getReturnValue() は、サーバから返された値を取得します。この例では、コールバック関数がユーザにサーバから返された値を含むアラートを表示します


({
    "echo" : function(cmp) {

        var action = cmp.get("c.serverEcho");
        action.setParams({ firstName : cmp.get("v.firstName") });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {

                alert("From server: " + response.getReturnValue());
            }
            else if (state === "INCOMPLETE") {

            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });

        $A.enqueueAction(action);
    }
})

APEX サーバ側

auraコンポーネント側からAPEX呼び出す時には必要な記載。
これが無いと呼び出せない。メソッドは必ずstatic。 AuraEnabled


public  class SimpleServerSideController {
    @AuraEnabled
    public static String serverEcho(String severName) {

        return ('サーバから返信しますね ');
    }
}

参考文献

setParams
http://www.jive-comp.co.jp/01jvrw/help/SetParamx83x81x83x5cx83x62x83x68.htm

コールバック関数とは??
https://sbfl.net/blog/2019/02/08/javascript-callback-func/

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up