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() { }
}
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)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With