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

How to split Json response and get specific part using angular

我正在使用 hyperledger composer 开发 angular 区块链应用程序 tool.When 我查询了历史学家,我得到了如下回复。

{

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

}

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

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

显示的部分是这样的

org.hyperledger.composer.system.AddParticipant

但我只想在没有 'org.hyperledger.composer.system.' 部分的响应中显示 'AddParticipant' 部分。我该如何解决?

为此,只需进行少量字符串操作。利用 JS .split() 方法按参数 character/string.

拆分字符串

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

然后 arr[arr.length-1] 是您需要的字符串部分,您可以将其绑定以查看。就像在模板绑定

中使用 {{txTyepe}}
this.txType = arr[arr.length-1];

您可以使用 "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));

也可以用正则表达式得到最后的"word":

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

当您看到您的历史数据时,它看起来像这样

'$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'。