How to fix http.post() is not sending the request with Angular?

Sometimes, we want to fix http.post() is not sending the request with Angular.

In this article, we’ll look at how to fix http.post() is not sending the request with Angular.

How to fix http.post() is not sending the request with Angular?

To fix http.post() is not sending the request with Angular, we call subscribe on the observable returned with http.post.

For instance, we write

import { Component, OnInit } from "@angular/core";
import { Http, RequestOptions, Headers } from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import { Post } from "./model/post";
import { Observable } from "rxjs/Observable";

@Component({
  templateUrl: "./test.html",
  selector: "test",
})
export class NgFor implements OnInit {
  posts: Observable<Post[]>;
  model: Post = new Post();
  //...
  constructor(private http: Http) {}

  ngOnInit() {
    this.list();
  }

  private list() {
    this.posts = this.http
      .get("http://localhost:3000/posts")
      .map((val, i) => <Post[]>val.json());
  }

  public addNewRecord() {
    const headers = new Headers({ "Content-Type": "application/json" });
    const options = new RequestOptions({ headers });

    this.http
      .post("http://localhost:3000/posts", this.model, options)
      .subscribe();
  }
}

to call this.http.post in addNewRecord to make a POST request to http://localhost:3000/posts.

We call it with the request body and request options as the 2nd and last arguments.

Then we call subscribe to make request.

We can call subscribe with a callback that has the request response as the parameter to get the response.

Conclusion

To fix http.post() is not sending the request with Angular, we call subscribe on the observable returned with http.post.