如何拆分Json响应并使用angular获得特定部分

时间:2018-09-22 14:42:01

标签: javascript angular hyperledger-fabric hyperledger hyperledger-composer

我正在使用Hyperledger Composer工具开发有角度的区块链应用程序。当我查询历史学家时,我得到了如下响应。

{

 transactionType:"org.hyperledger.composer.system.AddParticipant"

}

我使用以下代码段显示交易类型。

 <div class="col-md-6">
    {{participant.transactionType}}
 </div>

这样显示的部分。

org.hyperledger.composer.system.AddParticipant

但是我只想在响应中显示“ AddParticipant”部分,而没有“ org.hyperledger.composer.system”。部分。我该如何解决?

4 个答案:

答案 0 :(得分:0)

为此,只需执行少量字符串操作即可。利用JS .split()方法,该方法按参数字符/字符串分割字符串。

let arr = this.participant.transactionType.split(".");

然后arr[arr.length-1]是您需要绑定的字符串部分,您可以绑定该部分以查看。就像在模板绑定中{{txTyepe}}下使用

this.txType = arr[arr.length-1];

答案 1 :(得分:0)

您可以使用“ substr”从字符串中选择一个单词,但是首先需要在字符串中定位单词,因此:

const str = 'org.hyperledger.composer.system.AddParticipant'
let getPosition = str.indexOf('AddParticipant'); // get the position of AddParticipant
let getWord = str.substr(getPosition,13);

AddParticipant的长度为13
,您也可以更改上面的代码,以获得更好,更简洁和多用途的代码

const splitWord = (index)=>{
  const str = 'org.hyperledger.composer.system.AddParticipant'
  let strArray = str.split('.')
  let getPosition = str.indexOf('AddParticipant'); // get the position of AddParticipant
  let getWord = str.substr(getPosition,strArray[index].lenght); //you just need to change the number 

  return getWord;
}
console.log(splitWord(4));

答案 2 :(得分:0)

您还可以使用正则表达式获取最后一个“单词”:

<div class="col-md-6">
  {{participant.transactionType.match(/\w+$/i)}}
</div>

答案 3 :(得分:0)

当您查看历史数据时,它将看起来像这样

'$namespace': 'org.hyperledger.composer.system',
'$type': 'HistorianRecord',
'$identifier': '6e43b959c39bdd0c15fe45587a8dc866f1fa854d9fea8498536e84b45e281b31',
'$validator': ResourceValidator { options: {} },
transactionId: '6e43b959c39bdd0c15fe45587a8dc866f1fa854d9fea8498536e84b45e281b31',
transactionType: 'org.hyperledger.composer.system.IssueIdentity',
transactionInvoked:
 Relationship {
   '$modelManager': [Object],
   '$classDeclaration': [Object],
   '$namespace': 'org.hyperledger.composer.system',
   '$type': 'IssueIdentity',
   '$identifier': '6e43b959c39bdd0c15fe45587a8dc866f1fa854d9fea8498536e84b45e281b31',
   '$class': 'Relationship' },

因此,您可以使用 transactionInvoked 对象,而不是使用 transactionType 。然后,您可以从该对象获取所需的任何信息。 最后,您的代码应为

 <div class="col-md-6">
     {{participant.transactionInvoked.$type}}
 </div>

对于我来说,它将为我提供“ IssueIdentity”交易类型。