locnguyen
locnguyen

Reputation: 841

Angular 2 In Memory Web API - Cannot read property 'data' of null

Is it possible to post to url app/heroes/1/jobs

When I try to I get the error Cannot read property 'data' of null

createJob(hero: Hero, job: Job): Observable<Job> {
  const url = `${this.heroUrl}/${hero.id}/jobs`;
  return this.http.post(url, JSON.stringify(job), {headers: this.headers})
    .map(res => res.json().data)
    .catch(this.handleError);
}

Upvotes: 0

Views: 511

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 209004

It's currently not possible, without customizing it (which isn't really any easy task, but doable). What's happening is that the 1/jobs is taken to be the id of the heroes collection, and it will return null since the following is null

let heroes = [...]
let id = '1/jobs'
return heroes.find(hero => return hero.id === id);

Like I said, you can customize it, but it'll take some work. It would consist of overriding the parseUrl add adding a response interceptor or an interceptor for each HTTP method you want to override. You can see an example. It's explained somewhat in the docs.

I've been following the issues, and it seems like the maintainers pretty much feel this is more of a tool for demos and don't want to spend too much time trying to make this something that is robust and suitable for most cases. So they just make it customizeable, even though the customization is not really an easy task.

Upvotes: 2

Yaser
Yaser

Reputation: 5719

Try this:

.map((res:Response) => res.json().data)

Upvotes: -1

Related Questions