在Mule中的forEach内部访问变量

时间:2019-03-19 13:43:30

标签: mule mule-studio dataweave mule-esb

我有两个查询

  1. 假设如果我在forEach内声明了两个变量,例如flowVars.ABCflowVars.DEF,那么如何在forEach块之外访问这两个变量?

  2. 每个变量都有一个JSON负载,如何将这两个变量的数据添加到单个JSON负载中?

有人可以帮助我吗?我无法访问foreach内的变量并添加2个JSON。

这是我的示例代码

<flow name="test">
        <foreach doc:name="For Each">
            <scatter-gather doc:name="Scatter-Gather">
                <set-variable variableName="ABC" value="#[payload]" mimeType="application/json" doc:name="ABC"/>
                <set-variable variableName="DEF" value="#[payload]" mimeType="application/json" doc:name="DEF"/>
            </scatter-gather>
        </foreach>
        <set-payload value="#[flowVars.ABC + flowVars.DEF]" mimeType="application/json" doc:name="adding 2 vars"/>
    </flow>

1 个答案:

答案 0 :(得分:1)

You need to understand how scoping works with foreach. Any variables set inside the foreach scope will NOT be available outside of that scope. However, variables set outside of the foreach scope (e.g. a set-variable before the foreach) will be available inside the foreach scope. This should help you get around your issue. I'm taking out the scatter-gather because it really doesn't serve any purpose in your example:

<flow name="test">
    <set-variable variableName="ABC value="#[payload] mimeType="application/json" doc:name="ABC"/>
    <set-variable variableName="DEF value="#[payload] mimeType="application/json" doc:name="DEF"/>
    <foreach doc:name="For Each">
        <set-variable variableName="ABC" value="#[payload]" mimeType="application/json" doc:name="ABC"/>
        <set-variable variableName="DEF" value="#[payload]" mimeType="application/json" doc:name="DEF"/>
    </foreach>
    <set-payload value="#[flowVars.ABC ++ flowVars.DEF]" mimeType="application/json" doc:name="adding 2 vars"/>
</flow>

Beyond this, I'm not sure if your code is a simplification or not, but as it stands now there are a couple things that are questionable:

Why are you using a scatter-gather? If you don't really need to do multiple things asynchronously (like making calls to multiple services), it's just a complication in your code. Setting two vars doesn't qualify, in my opinion.

What is your code supposed to do? From my perspective it looks like you're just setting the payload to a duplicate of the last element in the original payload. If so you could just do this in a transformer:

%dw 2.0
output application/json
---
if (not isEmpty(payload))
  payload[-1] ++ payload[-1]
else
  []