Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Http / Jsonp Not Making Request

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.

like image 273
Gregg Avatar asked Sep 04 '26 12:09

Gregg


1 Answers

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); };
like image 66
Günter Zöchbauer Avatar answered Sep 06 '26 07:09

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!