Maciej Miśkiewicz
Maciej Miśkiewicz

Reputation: 412

Loop over Observable

In my frontend part of application use a method

this.knowledgeMan.getUserAllowedCases(Item.ItemNumber)

which returns Observable. On my backend part, this method returns a List<String>. My question is: how do I get to loop over the elements of this list of Strings?

Upvotes: 0

Views: 44

Answers (3)

Mike Tung
Mike Tung

Reputation: 4821

If you are using this List<String> observable to show on the HTML part you can use a combination of async and *ngFor to get the desired result.

//in your html for example
<ul>
  <li *ngFor="let item of (data$ | async)"> {{ item }} </li>
</ul>

//in your component

//usual angular stuff
export class MyComponent implements OnInit {
  data$: Observable<String[]>;
  constructor(private knowledgeMan: YourServiceInterface){}

  ngOnInit() {
    data$ = this.knowledgeMan.getUserAllowedCases(Item.ItemNumber);
  }
}

If you are just doing this to compute some value you can do this following.

this.knowledgeMan.getUserAllowedCases(Item.ItemNumber).pipe(
  flatMap(),
  map(item => //do something with item here)
).subscribe();

Upvotes: 1

J. Knabenschuh
J. Knabenschuh

Reputation: 765

If you have an observable you have to subscribe to it to get the actual value. Within subscribtion its up to you, here you can map or loop over your values.

this.knowledgeMan.getUserAllowedCases(Item.ItemNumber).subscribe(allowedCases => {
  allowedCases.map(allowedCase => {
    // your code here
  });
});

Upvotes: 1

Ric
Ric

Reputation: 13248

If as you say, getUserAllowedCases returns string[] then you can do this:

this.knowledgeMan.getUserAllowedCases(Item.ItemNumber).subscribe(x => {
  // assuming x is string[]
  for (const item of x) {
     // use item
  }
});

Upvotes: 0

Related Questions