如何在 Angular 应用程序中显示对象的数据?

问题描述 投票:0回答:3

我在显示 API 响应数据时遇到问题。我收到的数据是对象中的对象。我尝试通过

JSON.striginfy
显示数据,但数据不清晰。

我从 API 收到的数据:

JSON:

{"102":{"173":"AX","175":"ZX","179":"桑蒂亚","183":"XM","186":"闪避","189" :"C3","191":"盛宝","193":"Jumpy","194":"柏林戈","196":"Xsara","200":"C15","204":"跳线","206":"C8","208":"C5","216":"C2","218":"C4","222":"C1","224":"C6" ,"233":"C-Crosser","241":"尼莫","5007":"DS3","10194":"DS4","15270":"DS5","15382":"C-零","15411":"C-Elysée","16100":"SpaceTourer","16536":"MODEL","16693":"Berlingo Electric"},"103":{"244":"Tico ","245":"Nexia","246":"Espero","247":"赛车手","248":"伊万达","249":"卡洛斯","250":"Nubira", "252":"莱甘萨","254":"拉诺斯","255":"卢布林 3","256":"马蒂兹","257":"科兰多","259":"穆索"," 262":"主席","263":"塔库马","264":"马蒂兹二世","265":"拉诺斯二世","1997":"FSO","2001":"卢布林二世", "16537":"型号"},"104":{"266":"Cinquecento","267":"Punto","269":"布拉沃","271":"布拉瓦","273": "Coupé","274":"Barchetta","275":"尤利西斯","277":"Palio","278":"Multipla","281":"Croma","283":"Tempra ","289":"杜卡托","290":"Tipo","292":"Uno","294":"熊猫","295":"马雷亚","300":"126 P" ,"301":"Dobló","304":"Stilo","308":"Seicento","310":"想法","312":"Scudo","320":"Grande Punto", "326":"Linea","329":"500","331":"Fiorino","333":"Sedici","1987":"Strada","4936":"Punto Evo"," 4938":"Punto Actual","5011":"500C","5015":"Qubo","5102":"500 C","15202":"弗里蒙特","15274":"熊猫经典", "15416":"500L","15509":"500 L","15830":"500X","16124":"124 Spider","16125":"塔伦托","16195":"后卫", "16538":"车型"},"105":{"336":"嘉年华","337":"焦点","339":"护航","340":"蒙迪欧","346": "天蝎座","352":"过境","359":"塞拉","361":"猎户座","369":"卡","370":"探索者","372":"融合","374":"StreetKa","375":"Galaxy","377":"Tourneo","385":"Maverick","392":"Puma","402":"S-MAX ","406":"C-MAX","415":"Kuga","2016":"Ranger","15418":"B-MAX","15878":"野马","16170": "Edge","16390":"EcoSport","16539":"MODEL","16655":"Grand Tourneo"},"106":{"421":"思域","422":"爵士乐" ,"423":"HR-V","424":"前奏","425":"传奇","426":"航天飞机","427":"流","430":"S2000" ,"432":"CR-V","434":"雅阁","439":"Integra","450":"FR-V","456":"城市","466":"洞察力","5018":"CR-Z","16540":"MODEL","17088":"e"},"107":{"467":"口音","468":"Lantra" ,"469":"索纳塔","471":"H100","472":"Getz","474":"S 轿跑车","475":"小马","477":"轿跑车", "478":"加洛珀","480":"H1","486":"阿托斯","489":"XG","490":"Trajet","494":"圣达菲"," 496":"伊兰特","497":"图森","499":"矩阵","501":"特拉肯","508":"宏伟","515":"i30","520" :“i10”,“522”:“ix55”,“523”:“i20”,“4940”:“ix35”,“5220”:“ix20”,“5222”:“创世纪”,“5280”:“ Veloster","10198":"i40","15598":"大圣达菲","16171":"Ioniq","16307":"H350","16358":"科纳","16541":"型号","16677":"Kona Electric","16678":"Ioniq Electric"},"108":{"525":"Neon","526":"Stratus","527":"Vision" ,"528":"纽约客","529":"航海者","531":"PT Cruiser","532":"大航海者","533":"赛百灵","536":"萨拉托加","537":"Le Baron","539":"毒蛇","543":"300 M","551":"交火","554":"300 C","16542":"型号”},}

我通过

JSON.striginfy
显示的原始数据:

我的代码:

组件.ts

vehicleModels;
dataIsReady = false;

 constructor(
    private vehicleService: VehicleService,
  ) { }

 ngOnInit(): void {
    this.getModels();
}

 public getModels() {
    this.vehicleService.getBrandsModels().subscribe(({ models }) => {
      this.vehicleModels = JSON.stringify(models);
      this.dataIsReady = models;
      console.log(models);
    });
  }
}

组件.html

<div *ngIf="dataIsReady">
  <p>{{vehicleModels}}</p>
</div>

我希望在组件中显示这些数据,例如:

102:173-AX,175-ZX,
103:244 - 蒂科,245 - 尼克夏

如何正确显示该数据?

angular typescript angular-httpclient
3个回答
5
投票

您可以使用 keyvalue 管道在模板上使用以下代码来执行此操作:

<div *ngFor="let obj of vehicleModels | keyvalue">
    <div>
        <strong>{{obj.key}}:</strong>
    </div>
    <div *ngFor="let inner of obj.value | keyvalue" style="margin-left: 10px;">
        <span>{{inner.key}}</span> -
        <span>{{inner.value}}</span>
    </div>
</div>

2
投票

您可以尝试使用 Angular JSON 管道。

{{vehicleModels | json}}

但这不会完全按照您想要的方式格式化它。

API 数据很难处理,如果你可以控制它,你可以将其更改为类似这样的内容。

// these interfaces are probably completely wrongly names, i have no idea what your actual business data is called
interface Make {
  make_id: number
  make_name: string
}

interface Model {
  brand_id: number
  brand_name: string
  makes: Make[]
}

// mock service method -> returns an observable of mock data, i didn't want to set up an actual service
const getBrandsModels$ = (): Observable<Model[]> => {
  return of([
    {
      brand_id: 102,
      brand_name: 'CITOROEN',
      makes: [
        {
          make_id: 173,
          make_name: 'AX'
        },
        {
          make_id: 179,
          make_name: 'Xantia'
        }
      ]
    },
    {
      brand_id: 103,
      brand_name: 'DAEWOO',
      makes: [
        {
          make_id: 244,
          make_name: 'Tico'
        },
        {
          make_id: 245,
          make_name: 'Nexia'
        }
      ]
    }
  ])
}

@Component({
  template: `
    <!-- this is an async pipe, it basically replaces the subscribe stuff -->
    <div *ngIf="(brandModels$ | async) as brandModels">
      <!-- you can put the ngFor on a div but i've chosen to keep them separate so the code is easier to understand -->
      <ng-container *ngFor="let model of brandModels">
        <div>
          {{ model.brand_id }}: {{ model.brand_name }}
          <ng-container *ngFor="let make of model.makes">
            {{ make.make_id }} - {{ make.make_name }}
          </ng-container>
        </div>
      </ng-container>
    </div>
  `,
  styles: [],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DisplayModelsComponent implements OnInit {
  // i'd recommend using an observable and piping it into the template instead of subscribing
  brandModels$: Observable<Model[]>

  constructor() {}

  ngOnInit(): void {
    // just call for the data and store it in the local variable
    this.brandModels$ = getBrandsModels$()
  }
}



1
投票

我已按照您的要求进行了更改。


  public formatData(data) {
    const rootKeys = Object.keys(data);
    rootKeys.forEach(item => {
        Object.keys(data[item]);
    });
    this.finalArr = [];
    for (let rootKey in data) {
      if (data.hasOwnProperty(rootKey)) {
          this.finalArr.push({key: rootKey, value: []});
          for (let key in data[rootKey]) {
              if (data[rootKey].hasOwnProperty(key)) {
                this.finalArr[this.finalArr.length - 1].value.push(`${key} - ${data[rootKey][key]}`);
              }
          }
      }
    }
    console.log(this.finalArr);
  }

请参阅以下链接

https://stackblitz.com/edit/angular-ivy-igxben?file=src%2Fapp%2Fapp.component.html

© www.soinside.com 2019 - 2024. All rights reserved.