简体   繁体   中英

Angular with TypeScript- how do I handle business logic within an observable callback?

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!

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM