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?