1

I have an array and I need to display several random items from this array. Now the code looks like this, but I think that there simply should be two different services, one in another. my component looks like this:

  items: Item[];
  randomItems: Item[];

  ngOnInit() {
    this.someService.getItems().subscribe((items) => {
      this.items = items;
    });
    this.randomIndex(this.items);
  }

  randomItems(items: Item[]) {
    return this.randomItems = _.sample(items, _.random(9));
  }
}

interface Items {
  id: number,
  title: string,
  body: string
}

my html looks like this:

 <ul *ngFor="let item of items">
     <li>{{ item.id }}</li>
 </ul>

How can I make two different services from this code?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Tom
  • 85
  • 7
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor Mar 15 '19 at 18:32
  • @Tom Hello Tom. I have not been able to understand your problem. Could you please tell me what kind of services are you trying to build? – Abhijeet Chakravorty Mar 15 '19 at 18:42

1 Answers1

0

First move the call to randomIndex to inside the subscribe callback.

ngOnInit() {
  this.someService.getItems().subscribe((items) => {
    this.items = items;
    this.randomIndex(this.items);
  });
}

About your question:

How can I make two different services from this code?

You don't need to based on the code you have shown. If you do it is subjective as to how you refactor it. Your main defect is that you are not waiting on the service to respond to do something with the result and that is easily solved.

Igor
  • 60,821
  • 10
  • 100
  • 175