3

I started to create buttons and grids with given data. For that purpose I created an array with objects in it. With the data in the array I create button and grids dynamically but now I want to do the same but instead of using a local variable to build the grids I want to create them with given data by an API. My problem is that it return an Observable and not an array. I tried to transform the data and push it into an array but I get always errors.

I tried to use the take and tap operator but everything is crashing always. I cannot transform the data as I want such that it works again.

In app.component.ts

// I have to change this.gridService.items somehow that it fits with an API
  ngOnInit(): void {
    this.gridItems = this.gridService.items;
  }

In grid.service.ts the private variable _items should be replaced with an API-Call which returns the same data structure and content but it would be an Observable -- and there is where to problem begins...

Can anyone edit my project with some dummy code how it could possibly work, so I understand the logic?

I really would appreciate your help.

If any information is missing, please tell me! Thank you!

2 Answers 2

1

Cara! Thank you for the question. If I understood you correctly, you want to replace your this.gridItems = this.gridService.items; to the HTTP call.

I've prepared a stackblitz example with emulation of an API call.

My main idea is the usage of $async pipe with Observable<GridItem[]> instead of sync getting. Don't forget to handle errors from an API.

P.S. I'm waiting for your feedback.

3
  • Thank you! I will try to implement it that way! If I have any question left, I hope I can ask you :)
    – Cara
    Jul 4, 2019 at 7:32
  • Of course! I'm waiting for your questions. Good luck :) Jul 4, 2019 at 7:39
  • Hello again :-), I would like to ask you something if you would not mind. If I have another property in the grid.model.ts file in your project like id, how would I only access the property sBezeichnung in the grid.component.html when in my grid.component.ts the code changes to this.grid.map((line) => { matrix[line.nZeile - 1][line.nSpalte - 1] = [line.sBezeichnung, line.ID];} , so an Array of properties for one field - but I do only want to show one of them.
    – Cara
    Jul 11, 2019 at 12:00
1

Use async pipe on your observable result:

<div *ngFor="let item of items$ | async">{{ item | json }}</div>

$ on end of variable is convention for variable containing streamed data in case of angular observables.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.