如何在angular4中从服务返回数据

时间:2017-11-30 14:31:07

标签: javascript angular angular-services angular-http

来自Angular1x背景。我正在将我现有的应用程序迁移到Angular4

这就是我的ng4服务的样子

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;
})}}

从组件中使用上述服务。

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) */
}}

在Angular1X中,我曾经从ngService返回promise但是在angular4中怎么做?

3 个答案:

答案 0 :(得分:2)

您应该订阅组件中的observable,而不是服务。

在您的服务中

public GetPosts() : any{
   return this._http.get("https://jsonplaceholder.typicode.com/posts");
}

在你的组件中

this._dService.GetPosts().subscribe(data => {
    const posts = data.json();
    console.log(posts);
    // Do whatever you like with posts

)};

答案 1 :(得分:0)

订阅的调用应该在组件的代码

答案 2 :(得分:0)

constructor(private http:Http) { }

getPosts(){
    return this.http.get('https://jsonplaceholder.typicode.com/posts').map(
      (response: Response) => {
                    return response.json();
      }
    )
 }

在组件中: 你声明的最佳做法:

data : any; 

this._dService.GetPosts().subscribe(
      data => {this.data = data;
      console.log(this.books);},
      err => {console.log(err);},

      ()=> {console.log("terminated");}
    );