0

I am relatively new to Angular and Typescript and I am running into an issue with variable scope. I am looking to call a function to return an array of image paths and then set those to a different array variable.

    ngAfterContentInit() {
        const minImages = 6;
        const tempImgArr = this.getAllImages(function (imgArr){
            // randomize image order
            imgArr = shuffleArray(imgArr);

            //cut to 6
            imgArr = imgArr.slice(0,minImages);
            console.log(imgArr);   // this displays the correct data
            return imgArr;
        });
      console.log(tempImgArr);   // this shows undefined
    }

    getAllImages(cb) {
      let arrAllImg = [];
      this.http.get<any>(this.backendPath+"/api/").subscribe(
        data => {  
            data.forEach(e => {
                var apiObj = {
                    path: e.Media1,
                    txt: e.MessageTxt
                }
                arrAllImg.push(apiObj);
            });
            cb(arrAllImg);
        },
        error => {
            console.error('There was an error!', error)
            cb(arrAllImg);
        }
      )
    }

How can I define my tempImgArr to return the appropriate array?

Nate23VT
  • 383
  • 5
  • 22
  • Does this answer your question? [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) – jonrsharpe Mar 15 '20 at 18:26

1 Answers1

0

You are expecting to be able to return values from a subscription. Whenever you want to return observable values, you have to return the observable and subscribe higher up the call stack.

ngAfterContentInit() {
  const minImages = 6;
  this.getAllImages().subscribe((imgArr) => {
    // randomize image order
    imgArr = shuffleArray(imgArr);

    //cut to 6
    imgArr = imgArr.slice(0, minImages);
    console.log(imgArr);   // this displays the correct data

    // TODO: set local property?
  });
}

// return observable
getAllImages(): Observable<any[]> {
  return this.http.get<any>(this.backendPath + "/api/").pipe(
    map(data => data.map(e => ({
      path: e.Media1,
      txt: e.MessageTxt
    }))),
    catchError(error => {
      console.error('There was an error!', error);
      return of([]);
    })
  );
}
Kurt Hamilton
  • 10,583
  • 1
  • 14
  • 28