Coming from the Angular1x background.I am migrating my existing app to Angular4
This is how my ng4 Service looks like
import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
@Injectable()
export class DataService {
private _http : Http;
constructor(http:Http) {
this._http = http;
}
public GetPosts() : any{
this._http.get("https://jsonplaceholder.typicode.com/posts").subscribe(data => {
const posts = data.json();
console.log(posts); // logs the desired json
return posts;
})}}
Consuming the above service from the component.
import { Component, OnInit } from '@angular/core';
import {Customer} from './customer.model';
import {DataService } from '../../providers/data.service';
@Component({
selector: 'app-customer',
templateUrl: './customer.component.html',
styleUrls: ['./customer.component.css']
})
export class CustomerComponent implements OnInit {
private _dService: DataService;
constructor(dService:DataService) {
this._dService = dService;}
ngOnInit() {}
public GetAll(){
let posts =this._dService.GetPosts();
debugger;
console.log(posts); // undefined
/* here the posts is getting UNDEFINED (error) */
}}
In Angular1X, I used to return promise from ngService but how do the same in angular4??