简体   繁体   English

JSON 从 Apex 传递到 Lightning 组件并在数据表中显示

[英]JSON to be passed from Apex to Lightning Component and display it in a data table

Below is my JSON, out of which I need ID, StartTime,DurationMilliseconds,LogLength.下面是我的 JSON,其中我需要 ID、StartTime、DurationMilliseconds、LogLength。 Below is the code that I tried but it is returning only all the values in a single line.Any help would be apreciated:下面是我尝试过的代码,但它只返回一行中的所有值。任何帮助都将不胜感激:

{
   "size":6,
   "totalSize":6,
   "done":true,
   "queryLocator":null,
   "entityTypeName":"ApexLog",
   "records":[
      {
         "attributes":{
            "type":"ApexLog",
            "url":"/services/data/v50.0/tooling/sobjects/ApexLog/07L0o00005Y2fE1EAJ"
         },
         "Id":"07L0o00005Y2fE1EAJ",
         "StartTime":"2020-12-18T08:46:24.000+0000",
         "DurationMilliseconds":230,
         "LogLength":3883
      },
      {
         "attributes":{
            "type":"ApexLog",
            "url":"/services/data/v50.0/tooling/sobjects/ApexLog/07L0o00005Y2fE1EAJ"
         },
         "Id":"07L0o00005Y2fE1EAJ",
         "StartTime":"2020-12-18T08:46:24.000+0000",
         "DurationMilliseconds":230,
         "LogLength":3883
      }
   ]
}

================Controller.js================== ================Controller.js==================

({
    doInit : function(component, event, helper) {
        var action = component.get("c.GetLogs"); 
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {                
               
                var conts= JSON.stringify(response.getReturnValue());
                console.log(conts);
                var res=conts.split(',');
                
                console.log('alert'+res[0].replace('{',' '));
                component.set("v.record",res); 
            } 
    });           
        $A.enqueueAction(action);
    }
})

=====================Component================== =====================组件==================

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="DebugLogCallout">
    <!-- attributes -->
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="record" type="String[]" description="Debug Logs visible below"/>
     
    <!-- handlers-->
    <aura:handler name ="init" value ="{!this}" action = "{!c.doInit}"/>
    <div style="height: 300px">
        <!-- <lightning:datatable
            columns="{! v.columns }"
            data="{! v.records}"
            keyField="id"
            onrowaction="{! c.handleRowAction }"/> -->
    </div>
        <table class="slds-table slds-table_bordered slds-table_cell-buffer slds-table_col-bordered slds-table_striped">
            <thead>
                <tr class="slds-text-title_caps">
                    
                    <th scope="col">
                        <div title="Key">Key</div>
                    </th>
                    <th scope="col">
                        <div title="Value">Value</div>
                    </th>
                </tr>
            </thead>
            <tbody>
                
                <aura:iteration items="{!v.record}" var="opp" indexVar="key">
                    <tr>
                        
                        <th scope="col">
                            <div>{!opp}</div>
                        </th>
                        
                        
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
</aura:component>

========================Apex================= =========================Apex=================

public class DebugLogCallout {
    
    @AuraEnabled
    public static List<Object> GetLogs(){
        List<Object> objMap= new List<Object>();
        Map<String,Object> map1= new Map<String,Object>();  
        Map<String,Object> finalMap= new Map<String,Object>();  
        List<Map<string, object>> rec = new List<Map<String,Object>>();
        Map<string, object> attr = new Map<String,Object>();
        List<String> recIds = new List<String>();
        Http h = new Http();
        
        HttpRequest req = new HttpRequest();
        String FirstName = UserInfo.getFirstName();
        
        req.setHeader('Authorization', 'BASIC {!$Credential.OAuthToken}');
        req.setHeader('Content-Type', 'application/json');
        req.setEndpoint('callout:Debug_Log/services/data/v50.0/tooling/query/?q=Select+id,StartTime,DurationMilliseconds,LogLength+from+ApexLog+Where+LogUser.FirstName=\''+FirstName+'\'');
        req.setMethod('GET');
        system.debug(req);
        HttpResponse res = h.send(req);
        if (res.getStatusCode() == 200) {
            map1=(Map<String,Object>)JSON.deserializeUntyped(res.getBody());
            System.debug(res.getBody());
            System.debug('map1----'+map1);
             objMap = (List<Object>)map1.get('records');    
            System.debug('objMap----'+ObjMap);
            for(Object o : objMap)
            {
                attr = (Map<string, object>)o;                            
                attr.remove('attributes');
                rec.add(attr);
            }
        }      
        
        System.debug('strMapList'+rec);
        return rec;   
    }
}

=============================================================== ==================================================== ==============

This is the wrong way to handle JSON.这是处理 JSON 的错误方法。

            var conts= JSON.stringify(response.getReturnValue());
            console.log(conts);
            var res=conts.split(',');
            
            console.log('alert'+res[0].replace('{',' '));
            component.set("v.record",res); 
            

You're turning your JSON, a nice structured object that you can process easily in code, into a string, and then doing replaces on it.您正在将 JSON(一个结构良好的 object)转换为字符串,然后在其上进行替换。 Don't do that.不要那样做。

You really do not need to do any of the data manipulation you're currently doing.你真的不需要做任何你目前正在做的数据操作。 Simply return the entire response body from Apex:只需从 Apex 返回整个响应正文:

    HttpResponse res = h.send(req);
    if (res.getStatusCode() == 200) {
        return res.getBody();
        

and in JavaScript, extract the record data that you want:并在 JavaScript 中,提取您想要的记录数据:

        var state = response.getState();
        if (state === "SUCCESS") {                
            component.set("v.records", response.getReturnValue()["records"]); 
            

and wire your Lightning data table component up to the v.records attribute, with an appropriate column set for the record data.并将您的 Lightning 数据表组件连接到v.records属性,并为记录数据设置适当的列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 显示 JSON 字符串的 Lightning Web 组件不起作用 - Lightning Web Component to display JSON String is not working 无法从Lightning组件的帮助器类调用Apex控制器 - Not able to call apex controller from lightning component's helper class Json 响应将在 Apex salesforce 闪电中反序列化 - Json response to be deserialized in Apex salesforce lightning 如何将Javascript映射作为参数从闪电组件发送到Apex服务器控制器? - How to send Javascript map as a parameter from lightning component to Apex server controller? SalesForce 查询在查询编辑器中返回结果,但从 Lightning 组件中的 APEX 代码返回 null - SalesForce query returns results in Query Editor, but returns null from APEX code in Lightning component 无法更改 JS Object 中的属性作为 Lightning Web 组件中的 API 变量从父级传递 - Unable to Change attribute in JS Object passed from Parent as API Variable in Lightning Web Component 在闪电组件中显示 csv 数据 - Show csv data in lightning component 在没有顶点的闪电 web 组件上创建任务仅 javascript controller? - Create a task on a lightning web component without apex only javascript controller? Salesforce Lightning Component不会通过Apex调用更新记录,从而冻结 - Salesforce Lightning Component will not update records via Apex call, freezes 如何在 Lightning Web 组件数据表 URL 列中添加 onclick 功能 - How to add onclick functionality in lightning web component data table URL column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM