Reputation: 35864
I'm using Angular 2.0.0-beta.16
and attempting to get data from my RESTful API. I have the following service:
import {Injectable} from 'angular2/core';
import {Jsonp, Response, Headers, RequestOptions} from 'angular2/http';
import {Store} from './store';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class StoreService {
constructor(private jsonp: Jsonp) {
}
getStores(): Observable<Store[]> {
console.log("getting stores");
// let headers = new Headers({ 'Content-Type': 'application/json' });
// let options = new RequestOptions({ headers: headers });
return this.jsonp.get("http://localhost:8080/stores")
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
console.log(res.status);
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body.data || {};
}
private handleError(error: any) {
// In a real world app, we might send the error to remote logging infrastructure
let errMsg = error.message || 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
From my component, I'm calling getStores()
. I know it is getting into the getStores()
function because I am getting the console.log
message. However, nothing else happens. No request is being made that I can see in the chrome dev tools. No errors being logged to the console. Just nothing. I've tried both Jsonp
and Http
but they both give the same results.
Upvotes: 3
Views: 943
Reputation: 657058
You need to subscribe to the observable returned by getStores()
. Observables are lazy and don't do anything without subscribe()
or `toPromise()
getStores().subscribe(val => { console.log(val); };
Upvotes: 5