1

I'm trying to return an array from this TypeScript function (written within Angular).

I've tried a number of different approaches. I've tried having a public variable in the class that gets initialized with courses (say the variable was called public fallCourses : xCourse[] and in the function below it'd have this.fallCourses = courses), I've tried typing return before 'courses' within the function call below, etc. Pretty simple operation, just can't get it to work.

getFallCourses(){

    let fallCourses : xCourse[];
    this.dataService.getFallCourses().subscribe((courses: xCourse[]) => {
            fallCourses = courses;
    });  
    return fallCourses;   

}

beh1
  • 139
  • 1
  • 2
  • 15

1 Answers1

0

The observable is completing after the function returned, so it just replaces local scoped fallCourses. If you need this like it is, then you should return an array, which is filled in subscription. Here's a snippet:

getFallCourses(){
    let fallCourses: xCourse[] = [];

    this.dataService.getFallCourses().subscribe((courses: xCourse[]) => {
        fallCourses.push(...courses); // will change the fallCourses itself
    });  

    return fallCourses;
}

But it's better to use the observable itself, just by subscribing to it from the caller.

Krypt1
  • 1,066
  • 8
  • 14
  • I tried your suggestion but this returns an array of size 0. I guess I could put all of my code in the subcribe() function. What I’m trying to do is see if a certain string is present in the array that’s returned, and all I need to return from this is a Boolean. – beh1 May 15 '18 at 15:05
  • It will return an empty array, which will be filled during the `subscribe()` method. If you need the data right after calling `getFallCourses()`, then you must to change your code and put your logic inside the `.subscribe()`. – Krypt1 May 15 '18 at 15:08
  • Ok. If I do that, I need to pass in a string to the subscribe function and then have it return a Boolean if the string is in that array. Is it possible to do this with this syntax? – beh1 May 15 '18 at 15:25
  • Well I'm sure that it can be done with Observables, but I need to see the code to say how it can be changed to support the observables. As a reference you can check [Angular Docs](https://angular.io/guide/observables). Also you can check [here](How do I return the response from an Observable/http/async call in angular2?), which has a comprehensive answer. – Krypt1 May 15 '18 at 16:24