getClassesAndSubjects performs an asynchronous operation, so, when you call getClasses the operation has not yet finished. You need to return an observable or a promise from getClassesAndSubjects:
public getClassesAndSubjects(school: number, whenData: string): Observable<your-type> {
const observable = this.classService.GetClassesAndSubjects(school, whenDate);
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
return observable;
}
Now:
a.getClassesAndSubjects(1,'2018-01-01').subscribe(value => {
a.getClasses();
});
If a function performs asynchronous operations, any action that depends of the results of such operation, must take into account that, and wait for the operation to complete.
You can also use async/await. In this case, the asynchronous function must return a Promise:
public async getClassesAndSubjects(school: number, whenData: string): Promise<your-type> {
const observable = this.classService.GetClassesAndSubjects(school, whenDate);
observable.subscribe(data => {
if (!data.hasOwnProperty('errors')) {
this.classesSubjects = data;
}
}, error => {
console.log("ERROR loading GetClassesAndSubjects: " + error);
});
return observable.toPromise();
}
And now, wherever you want to use it:
async function whatever() {
// ...
await a.getClassesAndSubjects(1, '2018-01-01');
a.getClasses();
}
By doing this, the execution of function whatever gets suspended until the promise returned by a.getClassesAndSubjects is fulfilled or rejected, so, when a.getClasses is executed, the data is there. Of course, the fact that this function gets 'suspended' does not mean the application get suspended, too. What happens is that, under the hood, the async function gets broken into parts, and the second part (after the await) gets executed inside a Promise.then method. But the compiler doest that for you, so the solution is much more elegant.
You need to remember that any function in which you use await must be declared as async.
a.getClasses();inside:.subscribe(data => {}but I need call this outside