Reputation: 12015
I have Promise function that return data:
private initializePeriod(profile: Profile): Promise <any> {
return this.educationPeriod.getCurrentStudyPeriodPromise(profile.organization.id);
}
Where getCurrentStudyPeriodPromise()
get returns:
return this.http.post('', data).toPromise();
I call this promise like:
return this.initializePeriod(profile)
.then((currentPeriod) => {
console.log(currentPeriod);
});
Why I can undefined in console.log instead data from response?
Method request is:
public getCurrentStudyPeriodPromise(schoolId: number): Promise<any> {
const data = { '$type': 'ReadRequest', 'query': 'getCurrentStudyPeriod', 'parameters': {'school': schoolId} };
return this.http.post('', data).toPromise(); }
I tried to use Mockup to test this:
private initializePeriod(profile: Profile): Promise <any> {
return new Promise(resolve => {
this.educationPeriod.getCurrentStudyPeriodPromise(profile.organization.id).then(r => {
resolve({'a': 1});
}), e => {
reject(e);
};
});
}
So, I replaced resolve(r);
on resolve({'a': 1});
, and it works.
So, It means getCurrentStudyPeriodPromise
returns incorrect promise, it returns undefined
Upvotes: 0
Views: 472
Reputation: 1809
Sorry for putting this in an answer it's just a lot of code so...
but you could return an Observable and then subscribe to it
public getCurrentStudyPeriodPromise(schoolId: number): Observable<any> {
const data = { '$type': 'ReadRequest', 'query': 'getCurrentStudyPeriod', 'parameters': {'school': schoolId} };
return this.http.post('', data);
}
private initializePeriod(profile: Profile): Observable<any> {
return this.educationPeriod.getCurrentStudyPeriodPromise(profile.organization.id);
}
Then the method call would be
this.subscription = this.initializePeriod(profile)
.subscribe((currentPeriod) => {
console.log(currentPeriod);
});
return this.subscription
Only thing is you really need to make sure and unsubscribe, so later in ngOnDestroy lifecycle hook you could put
this.subcrption.unsubscribe();
I know it's not a promise so it might not be the way you want to go, but it's an option.
EDIT:
If you need to chain requests together you could do something like this, in this example I'm "creating a profile" then calling to get the profile that was just created.
onChainingRequests(): Observable<any> {
return this.http.post('profile/create', profile).pipe(
switchMap(createdProfileData => this.http.get(`getProfile?profileId=${createdProfileData.id}`));
)
}
In this scenario when you call the first http you use the rxjs observable pipe method, then the http.post returns data it will feed that as the parameter into the switchMap method (imported from 'rxjs/operators') the switchMap method then returns the second http.get call.
The result is when you call onChainingRequests() the returned data is whatever is returned from the second http request.
Upvotes: 1