Starboy
Starboy

Reputation: 1635

Angular 2 Http.Post not sending request

Trying to make a simple POST to my server, with some data and have it return some JSON data. (Currently, it runs through the call but I see nothing on my network tab that it actually tried to make it?)

My Service (api.service.ts)

import { Injectable }    from '@angular/core';
import { Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class ApiService {

	private headers = new Headers({'Content-Type': 'application/json'});
  	private myUrl = 'https://www.mywebsite.com';  // URL to web api
  	private payLoad = {"thingy1":"Value1", "thingy2":"value2"};

  	constructor(private http:Http) { }

  	getData () {
        this.http.post(this.myUrl, JSON.stringify(this.payLoad), this.headers)
        	.map((res:Response) => res.json())
            .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
    } 

}

Then I just have the getData method ran in a header component just to fire it. (header.component.ts)

import { Component, OnInit } from '@angular/core';

//Service
import { ApiService } from '../services/api.service';


@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})

export class HeaderComponent implements OnInit {

  constructor(private service:ApiService) { 
    this.service.getData(); //Fire getData from api.service
  }

  ngOnInit() { }

}

Upvotes: 12

Views: 6352

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

Observable are lazy, even if you initialize them, they will not be executed. At least one subscriber has to explicitly subscribe to that observable to listen to that stream. In short: They will only be executed when you subscribe to it.

this.service.getData().subscribe(
  (data) => console.log(data)
);

Upvotes: 15

Aniruddha Das
Aniruddha Das

Reputation: 21698

Make sure you are subscribing your observable data. The RxJS observer has 2 parts,

  • next() - it push data which is done by angular itself.
  • subscribe - you need in your component to get data from observable.

Try something below

this.service.getData().subscribe(
  (data) => {
   //process your data here
  }
);

Upvotes: 2

Related Questions