1

I am trying to make a simple get request following the angular docs: https://angular.io/docs/ts/latest/guide/server-communication.html

Still getting this error on line 15 in editor.

return this.http.get(this.heroesUrl)
            .map(this.extractData)

Please find full code here:

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

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()

export class EventListService {
    private heroesUrl = '/data.json';  // URL to web API
    constructor (private http: Http) {}
    getEvents (): Observable<Hero[]> {
        return this.http.get(this.heroesUrl)
            .map(this.extractData)
            .catch(this.handleError);
    }
    private extractData(res: Response): Hero[] {
        let body = res.json();
        return body.data || { } as Hero[];
    }
    private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

interface Hero {

}

Calling the getEvents method:

import { Component, OnInit } from '@angular/core';
import { EventListService } from '../services/event-list.service';

@Component({
    selector: "event-list",
    templateUrl: "./event-list/event-list.component.html",
    styleUrls: ["./event-list/event-list.component.css"],
    providers: [ EventListService ]
})

export class EventListComponent implements OnInit{
    showImage: boolean = true;
    searchString: string = "";
    eventList: any[] = [];
    constructor(private eventListService: EventListService) {
        eventListService.getEvents();
    }
    ngOnInit() {
        console.error("INIT");
    }
    toggleImage():void {
        this.showImage = !this.showImage;
    }
    ratingClicked(data) {
        console.error(data);
    }
}
Ayush Walia
  • 172
  • 1
  • 12
  • How are you calling the `getEvents()` from your component? – AT82 Feb 07 '17 at 20:16
  • Currently I am not calling the getEvents method. This file doesn't get transpiled, so haven't reached that part yet – Ayush Walia Feb 07 '17 at 20:17
  • could you just try and change the `.map(this.extractData)` to `.map(res => res.json())` just to try :) – AT82 Feb 07 '17 at 20:18
  • @AJT_82 Same issue. – Ayush Walia Feb 07 '17 at 20:19
  • Just show us the function where you call the getEvents function, if you have one. – AT82 Feb 07 '17 at 20:21
  • @AJT_82 I don't think it would make any difference as even when I am not calling / using this service, the file still shows a error. Still I have updated the question to include the code where I have called this service's method. – Ayush Walia Feb 07 '17 at 20:25
  • You ARE calling this service in your component, with `eventListService.getEvents();` in your component. Even though the code is not running, compiler evaluates your code and informs if there is errors. And there could be one error. The `eventListService.getEvents();` isn't subscribing to any data, even though you are returning from your service. Try: `eventListService.getEvents.subscribe(d => { this.eventList = d} )` and see if that helps :) – AT82 Feb 07 '17 at 20:44
  • and BTW... move the function from the constructor to `ngOnInit` instead :) http://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit – AT82 Feb 07 '17 at 20:48
  • Spamming here... ;) And your `eventList` should be of type `Hero[]` since you are sending an Observable of `Hero` array- – AT82 Feb 07 '17 at 20:52
  • what error are you getting? – nzjun90 Feb 07 '17 at 21:12

2 Answers2

0

Just subscribe to the service call, that is why it's not doing the request.

Change this:

export class EventListComponent implements OnInit{
    showImage: boolean = true;
    searchString: string = "";
    eventList: any[] = [];
    constructor(private eventListService: EventListService) {
        eventListService.getEvents();
    }
    ngOnInit() {
        console.error("INIT");
    }
    toggleImage():void {
        this.showImage = !this.showImage;
    }
    ratingClicked(data) {
        console.error(data);
    }
}

For this:

export class EventListComponent implements OnInit{
    showImage: boolean = true;
    searchString: string = "";
    eventList: any[] = [];
    constructor(private eventListService: EventListService) {
        eventListService.getEvents().subscribe((response:Hero[]) => {
           console.log(response);
        });
    }
    ngOnInit() {
        console.error("INIT");
    }
    toggleImage():void {
        this.showImage = !this.showImage;
    }
    ratingClicked(data) {
        console.error(data);
    }
}
dlcardozo
  • 3,953
  • 1
  • 18
  • 22
0

Your error could be here:

getEvents (): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
        .map(this.extractData)
        .catch(this.handleError);
}
private extractData(res: Response): Hero[] {
    ...
}

You see the missmatch. getEvents is returning an Observable of Hero Array, but your extractData is returning a Hero Array.

Just change your extractData to:

private extractData(res: Response) {
    let body = res.json();
    return body.data || { } 
}

and I would suggest you move the call of getEvents to ngOnInit instead of the constructor, as per reference here, so do this instead:

ngOnInit() {
    this.eventListService.getEvents()
      .subscribe(d => {
        this.eventList = d})
}

and eventList should be:

eventList: Hero[] = [];
Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167