1

I have a problem with my code which I hope someone here could help me understand and point me in the right direction. The issue is in nesting promises. A specific method needs to make two Http requests to the server - the second one after the first one accomplishes successfully, and the result of the second one should be resolved in the calling class.

Whenever using the pattern I show in my example in methods that contain a single Http call it worked as expected. Here is the code:

Service1:

public class Service1 extends IService1 {
    public PostData(url : string, data: any) : ng.IHttpPromise<any> { 
        return this.$http.Post(url, data);
    }

    public GetData (url : string) : ng.IHttpPromise<any> {
        return this.$http.Get(url);
    }
}

Service2:

public class Service2 extends IService2 {
    private srv1 : IService1;

    static inject = ["Service1"];

    public constructor(service1){
        this.srv1 = service1;
    }

    public GetLetters(ids : number[]) : ng.IHttpPromise<any>{
        var scope = this;
        return this.srv1.PostData("api/letters", ids).success(function (data){
            return scope.srv1.GetData("api/lettters/" + data);
        })
    }
}

Controller

public class Controller1 {

    private service2 : IService2;
    private array : Letter[];

    static inject = ['Service2']

    public constructor (Service2 : IService2){
        this.service2 = Service2;
    }

    public someFunc() : void 
        var scope = this;
        // I have problems here when I try to retrieve the letters 
        this.service2.GetLetters(someIds).success((data) => {
            array = data;
        });
    }
}

Is there a different approach I should take here? The data inside the controller is the resolved data from the outer promise of the GetLetters method. I want to get the resolved data of the inner promise

1 Answer 1

1

A Service2 method GetLetters should return something..

public class Service2 extends IService2 {
    ...

    public GetLetters(ids : number[]) : ng.IHttpPromise<any>{
        var scope = this;
        //this.srv1.PostData("api/letters", ids).success(function (data){
        return this.srv1.PostData("api/letters", ids).success(function (data){
            return scope.srv1.GetData("api/lettters/" + data);
        })

Otherwise it is just evaluated...

Sign up to request clarification or add additional context in comments.

1 Comment

My bad, I forgot to mention the return before the Post method. I also use a .then in the controller. Fixed. Regarding your answer, by making a return statement in both functions, will it achieve my goal? The resolved data in the Controller will have the Letters?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.