1

I am Using JSONPlace holder Fake API for fetching data. I am getting the api data in service but if I call that service from my app component I am getting undefined why this is my code

My Service.ts is

import { Injectable } from '@angular/core';
import { Http, URLSearchParams, Response, RequestOptions, Headers } from '@angular/http';
import 'rxjs/RX';
import 'rxjs/add/operator/map';
@Injectable()
export class Service {
    apiRoot: string = 'https://jsonplaceholder.typicode.com/comments?' 
    postId = 1;
    data;
    constructor(private _http: Http) {
        this._http.get(this.apiRoot).subscribe((data) => {
            this.data = data.json();
        });
    }
    init() {
        return this.data;
    }

}

My component code is

import { Component, OnInit } from '@angular/core'; import { InfiniteService } from './infinite.service'; //import all rxjs/Rx opeartor  import 'rxjs/add/operator/map';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit {
    data;
    constructor(private _infinteService: InfiniteService) {
        this.data = this._infinteService.init();
        console.log(this.data);
    }

    GetPosition($event) {
        if ($event == 'Bottom') {
            console.log($event);
        }
        else {
            console.log($event);
        }
    }
    ngOnInit() { }

}

why I am not able to get service data in component?

4 Answers 4

3

Because HTTP its async function! I recommend to use HttpClient, so you don't need to use map function! You can try that

getData(): Observable<any> {
 return this._http.get(this.apiRoot)
}

And you just call him in component like that

this._infinteService.getData().subscribe(
 data => console.log(data)
)

You need to return an Observable, and then you can use subscribe to call request. Try that and tell if worked! Thanks

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

Comments

2

Make following changes in your code.

Service :

constructor(private _http: Http) {
}
init() {
    return this._http.get(this.apiRoot);
}

Component :

constructor(private _infinteService: InfiniteService) {
    this._infinteService.init().subscribe((data) => {
        this.data = data;
        console.log(this.data);
    });
}

You need to use .subscribe in component call.

4 Comments

What is the issue? Can you tell me whats in console.log?
I tried same in my system, Works nicely. Try changing this.apiRoot with sample URL.
yes Thanks i have changed the api now it is working fine Thank you!
Great. Glad we could help.
1

You don't need the .json() on your data object. As of Angular4 the default responseType is JSON and the response data is already parsed for us.

You should return the Observable from your service and subscribe to it in your component.

Comments

0

The reason for this occur is it will take some time to get the response from the server. So we can set it in promises. use the following command to get data in promises.

 this._customerService.getCustomers().subscribe(data => this.customers = data);

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.