Reputation: 718
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?
Upvotes: 2
Views: 1670
Reputation: 1387
From response.json().data
remove .data
and add || {}
if body is null
Finally:
.then((response: Response) => response.json() || {})
Upvotes: 1
Reputation: 362
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): [{...}, {...}, ...]
.
Upvotes: 1
Reputation: 14564
response.json() already gives you back the data object of your response as JSON, so remove the .data property access.
Upvotes: 5