Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() { }

}
like image 955
Starboy Avatar asked Dec 28 '16 03:12

Starboy


1 Answers

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)
);
like image 197
Pankaj Parkar Avatar answered Oct 01 '22 20:10

Pankaj Parkar