Problem with HTTP Post


#1

Hi,
I’m trying to sending POST data through angular’s http service but only blank data is being sent. I’ve made connection with the API so CORS isn’t the problem, and i’m sucessfuly getting the data from the form, but the data isn’t being sent to the API.
Can you please try to figure out what’s wrong?


And can someone explain to me what does the “subscribe” and “map” of http do?


#2

Wow, you may have learned about this months ago, but for the sake of other people getting started with observables. Observables are the new Angular2 preferred way of managing incoming and outcoming data streams (Events, http requests, forms). In many scenarios promises are quite rigid, and don’t enable advanced operations on handling of flying requests. For instance you can “subscribe” to a request, but maybe you are expecting it to come back in up to 2 seconds, or maybe you want to delay , so with observables you could delay the execution of the httprequest or cancel a flying one, to be sure that it doesn’t come back when you are not expecting it anymore. Unlike promises, observables can emit a sequence of values, you can “hear”, and do whatever you want.

In an ideal scenario, you’d create your Observable to handle and “unpack” http requests, so your consumer component, doesn’t know nothing about how/from your data is fetched, to enable decoupling of concerns.

Here’s an example for a “User” service

    public saveUser(user: User): Observable<boolean> {
        return this._http.post("http://yourapi.net/api/user/save", user)
            .map(res => this.saveUserOnSuccess(res))
            .catch((err, obs) => this.OnError(err, obs));
    }

    private saveUserOnSuccess(res: Response): boolean {
        let body = res.json();
        return body.success;
    }

and from the component

this.userService.saveUser(user)
                        .subscribe((result: bool) => {
                                   // Everything went ok!
                            });
                        }, (err) => {
                                // Save failed due to the err
                        })

It is also recommended that you follow the “Response” spec and data structure for responses from your api, to simplify unpacking. Remember to unsubscribe from the request. And you can always turn an observable in an common Promise, using observable toPromise() method and keep doing the way you may be doing things now.