微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从 Apex 传递到 Lightning 组件的 JSON 并将其显示在数据表中

下面是我的 JSON,其中我需要 ID、StartTime、DurationMilliseconds、LogLength。下面是我尝试过的代码,但它只返回一行中的所有值。任何帮助都会受到赞赏:

{
   "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","LogLength":3883
      }
   ]
}

================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);
    }
})

======================组件==================

<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==================

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;   
    }
}

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

解决方法

这是处理 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); 
            

您正在将 JSON(一个可以在代码中轻松处理的良好结构化对象)转换为字符串,然后对其进行替换。不要那样做。

您确实不需要进行当前正在进行的任何数据操作。只需从 Apex 返回整个响应正文:

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

并在 JavaScript 中提取所需的记录数据:

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

并将您的 Lightning 数据表组件连接到 v.records 属性,并为记录数据设置适当的列。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。