Hi I've built a project up with Angular-cli and I'm using express to serve API routes locally. I have a proxy setup so the angular client can reach the express server.
The issue I'm having is retrieving data from my API route and passing it to my view. I've tracked my data in my service and can see my observable is requesting/receiving the data objects fine. I've also used mock data and have seen my view/component is displaying the data correctly.
Is there something I'm missing to help the HTTP request transfer from Observable to Subscribe? My project doesn't show any errors and I'm unsure how to test my app within the observable/subscribe.
I have an almost identical setup on another project (the only difference being the HTTP request is being made to a local JSON file where this project is requesting it through and express URL) and that project works fine.
Here is my code.
Service
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
export interface Session {
title: string,
date: string,
description: string,
imageUrl: string,
thumbImageUrl: string,
audioUrl: string,
tracklist: [{
title: string,
artist: string
}]
}
@Injectable()
export class DashboardService {
private sessionsUrl = 'api/sessions';
constructor(private http: Http) { }
getSessions(): Observable<Session[]> {
return this.http.get(this.sessionsUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
console.log(res.json()); // THIS SHOWS THAT THE JSON OBJECT IS BEING RETURNED
let body = res.json();
return body.project;
}
private handleError(error: Response | any) {
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);
}
}
Component
import { Component, OnInit } from '@angular/core';
import { Session, DashboardService } from '../dashboard.service';
@Component({
selector: 'sessions-display',
templateUrl: './sessions-display.component.html',
styleUrls: ['./sessions-display.component.scss']
})
export class SessionsDisplayComponent implements OnInit {
sessions: Session[] = [];
errorMessage: string;
constructor(private dashboardService: DashboardService) { }
ngOnInit() {
this.getSessions();
}
getSessions() {
this.dashboardService.getSessions()
.subscribe(
sessions => this.sessions = sessions,
error => this.errorMessage = <any>error);
}
}
Here is an image of the console.log showing the res object.
