0

I'm trying to get some data and return something on success using an Angular HttpClient call like this:

    return this.http.post('api/my-route', model).subscribe(

        data => (
            this.data = data;
            return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
        )
    )

Why can't I do this? My app is Angular 4.3 with TypeScript 2.6.2 My understanding is that the arrow function should be the equivalent of this callback:

function(data) {
        this.data = data;
        return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
}

... and I'm treating 'data' like it will work as a 'success' callback in JQuery AJAX. Is a subscribe somehow limited to setting values of of properties within the class? What's wrong with my arrow function? I know I'm missing something basic!

1
  • 1
    Two remarks: (1) data => ( ... ) should be replaced with data => { ... }, (2) subscribe() returns a Subscription instance (often used to call its unsubscribe method), not the value returned by the callback function. Commented Feb 28, 2018 at 2:20

1 Answer 1

3

You can only use () if the "body" is an expression. Your "body" are two statements:

return this.http.post('api/my-route', model).subscribe(
    data => (
        this.data = data;
        return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
    )
)

Should be:

return this.http.post('api/my-route', model).subscribe(
    data => {                                                    // <==== changed this line
        this.data = data;
        return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
    }                                                            // <==== changed this line
)


The return statement

It seems you just want to perform the assignment, not return any value. If that's the case, just remove the return keyword from that last statement.


If, on the other hand, you really do also want to return that value to the caller of that function, don't use subscribe, but other function that will just transform the Observable, such as map:

public myMethod(): Observable<any> {
  // ... create the model variable
  return this.http.post('api/my-route', model).map(
    data => {
        this.data = data;
        return $window.location = ReturnUrlService.getAbsolute('/my-other-route');
    }
  )
}

Of course, remember to subscribe to the result wherever you call myMethod:

public someOtherMethod() {
  return this.myMethod().subscribe(stuff => console.log(stuff));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.