有没有一种方法可以显示api数据,而id密钥是从另一个密钥获取的呢?

时间:2019-03-27 13:43:29

标签: json angular api angular7

JSON数据:

"abcd":[
      {
        "id":"1",
        "cityId":"2",
      },
      {
        "id":"2",
        "cityId":"3",
      }         
],

"city":[
      {
        "id":"2",
        "cityName":"california"
      },
      {
        "id":"3",
        "cityName":"vicecity"
      }
]

角度:

<div *ngFor="let clg of abcd$">
  <p>
 {{clg.cityId}} 
<!-- Here i need to print the cityname from city by using the cityId we have got from abcd -->

  </p>
</div>

app.component.ts:

ngOnInit() {

    this.data.getColleges().subscribe(
      data => this.abcd$ = data
    )
}

从“ abcd”中获取数据是完美的工作...。从“ city”中获取数据也没有问题。但是可以通过使用“ abcd”部分中的cityId键从“ city”中获取cityName。

2 个答案:

答案 0 :(得分:0)

您可以使用一种通过ID获取城市的方法:

app.component.ts:

getCityByID = (cityID) => {
  return this.city$.find(item => item.id === cityID);
}

模板:

<div *ngFor="let clg of abcd$">
  <p>

    {{ clg.cityId }} 

    {{ getCityByID(clg.cityId).cityName }}

  </p>
</div>

更新

据我了解,您正在使用两个独立的观测值来获取大学和城市。因此,当您尝试通过ID获取城市时,如果尚未解决第二可观察的问题,它可能会(或可能不会)引发错误。因此,您需要将这两个流组合在一起。我更喜欢combineLatest来执行此操作,但是forkJoin也可以工作。

在app.component.ts中:

import { combineLatest } from 'rxjs';
......

ngOnInit() {

    combineLatest(
         this.data.getColleges(),
         this.data.getCity()
    ).subscribe(([colleges, cities]) => {
         this.abcd$ = colleges;
         this.city$ = cities;
     });
}

这样,您可以确保同时初始化abcd$city$。希望这会有所帮助。

进一步阅读:

combine最新:https://www.learnrxjs.io/operators/combination/combinelatest.html

forkJoin:https://www.learnrxjs.io/operators/combination/forkjoin.html

答案 1 :(得分:0)

尝试一下

<div *ngFor="let clg of abcd$">
    <p>
        {{clg.cityId}} 
        <span *ngFor="let c of city" [hidden]="c.id!=clg.id">
            {{c.cityName}}
        </span>  
    </p>
</div>