user7117607 user7117607 - 28 days ago 7
Javascript Question

what's wrong with this angular 2 service implementation?

The following Angular2 JobService implementation returns the error "job.service.ts:26 An error occurred Response {_body: Object, status: 404, ok: false, statusText: "Not Found", headers: Headers…}". The jobsUrl variable defined in the service returns a json result for a jobs result when submitted directly through a browser address bar. Any idea what the issue might be?

import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { JobsResult } from './jobs-result';

@Injectable()
export class JobService {

private headers = new Headers({'Content-Type': 'application/json'});
private jobsUrl = 'http://service.dice.com/api/rest/jobsearch/v1/simple.json?text=javascript';
//private jobsUrl = 'app/jobs'; // URL to web api

constructor(private http: Http) { }

getJobs(): Promise<JobsResult>{
return this.http.get(this.jobsUrl)
.toPromise()
.then(response => response.json().data as JobsResult)
.catch(this.handleError);
}

private handleError(error: any): Promise<any> {
console.error('getJobs() not working');
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}

Answer

data is undefined, response doesn't have data as key

.then(response => response.json() as JobsResult)

instead of

.then(response => response.json().data as JobsResult)
Comments