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

时间:2021-03-12 17:21:58

标签: angular typescript api httpclient

我在显示来自 API 响应的数据时遇到问题。我收到的数据是对象中的对象。我尝试通过 JSON.striginfy 显示数据,但数据不清楚。

我从 api 收到的数据: enter image description here

JSON:

{"102":{"173":"AX","175":"ZX","179":"Xantia","183":"XM","186":"Evasion","189":"C3","191":"Saxo","193":"Jumpy","194":"Berlingo","196":"Xsara","200":"C15","204":"Jumper","206":"C8","208":"C5","216":"C2","218":"C4","222":"C1","224":"C6","233":"C-Crosser","241":"Nemo","5007":"DS3","10194":"DS4","15270":"DS5","15382":"C-Zero","15411":"C-Elysée","16100":"SpaceTourer","16536":"MODEL","16693":"Berlingo Electric"},"103":{"244":"Tico","245":"Nexia","246":"Espero","247":"Racer","248":"Evanda","249":"Kalos","250":"Nubira","252":"Leganza","254":"Lanos","255":"Lublin 3","256":"Matiz","257":"Korando","259":"Musso","262":"Chairman","263":"Tacuma","264":"Matiz II","265":"Lanos II","1997":"FSO","2001":"Lublin II","16537":"MODEL"},"104":{"266":"Cinquecento","267":"Punto","269":"Bravo","271":"Brava","273":"Coupé","274":"Barchetta","275":"Ulysse","277":"Palio","278":"Multipla","281":"Croma","283":"Tempra","289":"Ducato","290":"Tipo","292":"Uno","294":"Panda","295":"Marea","300":"126 P","301":"Dobló","304":"Stilo","308":"Seicento","310":"Idea","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":"Freemont","15274":"Panda Classic","15416":"500L","15509":"500 L","15830":"500X","16124":"124 Spider","16125":"Talento","16195":"Fullback","16538":"MODEL"},"105":{"336":"Fiesta","337":"Focus","339":"Escort","340":"Mondeo","346":"Scorpio","352":"Transit","359":"Sierra","361":"Orion","369":"Ka","370":"Explorer","372":"Fusion","374":"StreetKa","375":"Galaxy","377":"Tourneo","385":"Maverick","392":"Puma","402":"S-MAX","406":"C-MAX","415":"Kuga","2016":"Ranger","15418":"B-MAX","15878":"Mustang","16170":"Edge","16390":"EcoSport","16539":"MODEL","16655":"Grand Tourneo"},"106":{"421":"Civic","422":"Jazz","423":"HR-V","424":"Prelude","425":"Legend","426":"Shuttle","427":"Stream","430":"S2000","432":"CR-V","434":"Accord","439":"Integra","450":"FR-V","456":"City","466":"Insight","5018":"CR-Z","16540":"MODEL","17088":"e"},"107":{"467":"Accent","468":"Lantra","469":"Sonata","471":"H100","472":"Getz","474":"S Coupe","475":"Pony","477":"Coupe","478":"Galloper","480":"H1","486":"Atos","489":"XG","490":"Trajet","494":"Santa Fe","496":"Elantra","497":"Tucson","499":"Matrix","501":"Terracan","508":"Grandeur","515":"i30","520":"i10","522":"ix55","523":"i20","4940":"ix35","5220":"ix20","5222":"Genesis","5280":"Veloster","10198":"i40","15598":"Grand Santa Fe","16171":"Ioniq","16307":"H350","16358":"Kona","16541":"MODEL","16677":"Kona Electric","16678":"Ioniq Electric"},"108":{"525":"Neon","526":"Stratus","527":"Vision","528":"New Yorker","529":"Voyager","531":"PT Cruiser","532":"Grand Voyager","533":"Sebring","536":"Saratoga","537":"Le Baron","539":"Viper","543":"300 M","551":"Crossfire","554":"300 C","16542":"MODEL"},}

我通过 JSON.striginfy 显示的原始数据: enter image description here

我的代码:

component.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);
    });
  }
}

component.html

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

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

102: 173 - AX, 175 - ZX,

103: 244 - Tico, 245 - Nexia

如何正确显示这些数据?

3 个答案:

答案 0 :(得分:4)

您可以通过使用键值管道在模板上使用以下代码来实现:

<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>

答案 1 :(得分: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

enter image description here

答案 2 :(得分:1)

您可以尝试使用 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$()
  }
}