首页 > 解决方案 > Angular 9 - 如何根据路线动态显示json的一部分

问题描述

大家好,我有点卡住了,希望你能提供帮助。所以,我想根据我所在的路线只显示 Json 的一部分。那个 Json 可能看起来像这样:

[
  {
    "Key": "string",
    "Rule1": [
      {}
    ],
    "Rule2" : [
       {}    
    ]
}
]

到目前为止,我已经设法在使 json 可折叠的指令中显示所有 json。

因此,当我单击选项卡时,我只想显示该 json 的一部分。示例:我单击“key”选项卡,我只得到了“key”json 属性中的内容,依此类推……我得到了 3 个组件:property、propertyTab 和 jsondisplay(没有提到指令)。在我的属性组件中,我放在模板文件的顶部:

<app-property-tab [property]="property"></app-property-tab>

这是我的 propertytab ts 文件:

export class PropertyTabComponent implements OnInit {

    Key: string;
    @Input() property: Property;

  constructor(private router: Router, private route: ActivatedRoute, private blablaService: blablaService) { }

  ngOnInit() {
    this.route.params
    .subscribe(
      (params: Params) => {
        this.Key = params['Key'];
        this.property = this.blablaService.getProperty(this.Key);
      }
    );
  }

  onWatchRule1(){
      this.router.navigate([`blabla/${this.propertyKey}`])
  }

  onWatchRule2(){
    this.router.navigate([`blabla2/${this.propertyKey}`])
}

}

我的模板很简单:

<li>
    <a (click)="Rule1()" >
        Rule1
    </a>
</li>
<li>
    <a(click)="onWatchRule2()">
        Rule2
    </a>
</li>

还有我的 jsondisplay 组件:

export class JsonDisplayComponent implements OnInit {
    allData: any;
    name: any;
    Key: string;
    @Input() property: Property;

  constructor(
    private route: ActivatedRoute,
    private blablaService: blablaService,
    private jsonDisplayService: JsonDisplayService) { }

  ngOnInit() {
      this.route.params
      .subscribe(
          (params: Params) => {
            this.propertyKey = params['propertyKey'];
            this.property = this.blablaService.getProperty(this.Key);
          }
      );

      this.jsonDisplayService.getProperty(this.Key).subscribe((data: any) => {
          this.allData = data;
          this.name = data.Key;
          console.log(this.allData)
      })

  }

}

和模板:

<app-property-tab [property]="property"></app-property-tab>

<h3>{{ allData.propertyKey }}</h3>

<br/>
<div class="ats-form-group ml-4"  style="height: 100%; background-color: white;" *ngFor="let data of [allData]">
    <div [appJsonFormatter]="data.rule"></div>
</div>

所以,我想知道的是如何根据我们单击的选项卡仅显示该 json 的一部分。因为我在这里唯一能做的就是获取所有 json 或一部分,但绝不是动态的,也绝不是当我单击选项卡时。任何帮助将不胜感激,谢谢。

标签: javascriptangulartypescript

解决方案


推荐阅读