-1

I have http.get and it's impossible for me to create array of objects. Can you help me ? I need to create loop on array of returned objects and i can't do this.

export class Link {
  idStat: String;
  idAccount: String;
}

links: Link [];

router.get('/linkGetAll', function(req, res, next) {
  Link.find(function (err, products) {
  if (err) return next(err);
    res.json(products);
  });
});

getAllLinks(){
  return this.http.get('/main/linkGetAll');
}

 this.api.getAllLinks().subscribe((data) => {
  this.links = data;
})

for(let item in this.links)
{
  DOESN'T WORK
}
devio95
  • 9
  • 1
  • 4
  • What do you receive in "data" exactly? Also this.links will be filled once subscribe returns data from "getAllLinks" call. Try to put your for loop inside .subscribe((data) => { block – robert Jan 19 '19 at 17:37
  • mongodb table data – devio95 Jan 19 '19 at 17:39
  • Observables are *asynchronous*, that's the whole point. If you want to access the data, do it in the callback. – jonrsharpe Jan 19 '19 at 17:48
  • Possible duplicate of [Angular 2 return data from service is not availabe after RxJs subscribe](https://stackoverflow.com/questions/37853620/angular-2-return-data-from-service-is-not-availabe-after-rxjs-subscribe) – jonrsharpe Jan 19 '19 at 17:50

2 Answers2

0
getAllLinks(){
  return this.http.get('/main/linkGetAll')
    .pipe(map(res => {

       // do something here
       // res.forEach() or res.map()
       return 'it';
     })
   );
}

Before going to

for(let item in this.links) { DOESN'T WORK }

Ensure that this.links has data in it.(use async/await along with toPromise())

skdonthi
  • 1,308
  • 1
  • 18
  • 31
0

Please read this section about HTTP of the Angular tutorial and the Angular API.

The get method accepts a type:

get<T>(...): Observable<T>

so you could modify your implementation of getAllLinks:

getAllLinks(): Observable<Link[] {
    return this.http.get<Link[]>('/main/linkGetAll');
}

Now you should should be able to iterate the response:

getAllLinks().subscribe(links => {
    links.forEach(link => // do what you need);
}
pedmer
  • 36
  • 3