2

I'm trying to get an angular 2 service to retrieve data from an HTTP request and return it as a promise. When I use the service in the component, the data I'm passing from the service is returned as undefined.

This is my service

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

@Injectable()

export class RecordService {
  constructor(private http: Http) {}
  getPosts(): Promise<any> {
    return this.http
      .get('https://jsonplaceholder.typicode.com/posts')
      .toPromise()
      .then((response: Response) => response.json().data)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    console.log('ERROR');
    return Promise.reject(error.message || error);
  }
}

and this is my component

import { Component, OnInit } from '@angular/core';
import { RecordService } from './record.service';
import { Router } from '@angular/router';

@Component({
    selector: 'record-view',
    template: '<h1>This is the record creation page</h1>',
    providers: [RecordService]
})

export class RecordComponent implements OnInit{
    message: string;
    error: any;

    constructor(private recordService: RecordService) { 

    }

    ngOnInit() {
        this.recordService.getPosts()
            .then(data => console.log(data))
            .catch(error => console.log(error));
    }
}

Any ideas why the data would be undefined?

3 Answers 3

5

response.json() already gives you back the data object of your response as JSON, so remove the .data property access.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was a much simpler solution than I was expecting!
1

When you response.json() the result is the exact content from the response of the request you made.

In this case, https://jsonplaceholder.typicode.com/posts returns an array (if open the url in a browser you'll see the array): [{...}, {...}, ...].

1 Comment

JSON can also be an array.
1

From response.json().data remove .data and add || {} if body is null

Finally:

.then((response: Response) => response.json() || {})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.