Angular 5 - HttpClient服务 - 组件无法获取数据

时间:2018-01-08 15:03:03

标签: javascript angular typescript angular-services angular5

我正在使用Angular 5并尝试从JsonPlaceholder获取一些数据。

首先我创建了服务,然后添加了:

import { HttpClientModule } from '@angular/common/http';

这是服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  private ROOT_URL = 'http://jsonplaceholder.typicode.com';

  constructor(private http: HttpClient) {}

  getPosts() {
    this.http.get(`${this.ROOT_URL}/posts`).subscribe(data => {
      return data;
    });
  }

}

最后,在我的app.component.ts上:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';

@Component({
  selector: 'app-root',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {

  data;

  constructor(private dataService: DataService) {

    this.data = dataService.getPosts();
    console.log(this.data;
  }

  ngOnInit() {
  }

}

在控制台上,它只是返回' Undefined'

我做错了什么?

5 个答案:

答案 0 :(得分:2)

不要订阅服务,返回observable并在组件上订阅它。因为它是异步的,所以组件上的数据变量将是未定义的,因为您在http请求可以解析值之前分配了它。

关于服务:

getPosts() {
    return this.http.get(`${this.ROOT_URL}/posts`);
}

在共同作者:

ngOnInit() {
    this.dataService.getPosts().subscribe(posts => this.posts = posts);
}

答案 1 :(得分:0)

import { HttpClientModule } from '@angular/common/http';
//This is the service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  private ROOT_URL = 'http://jsonplaceholder.typicode.com';

  constructor(private http: HttpClient) {}

  getPosts() {
  //if you want to use the observable which returns from .get()
  //.. you need to do "return"
   return this.http.get(`${this.ROOT_URL}/posts`);
  }

}
 
//app.component.ts:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';

@Component({
  selector: 'app-root',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {

  data;

  constructor(private dataService: DataService) {

    this.data = dataService.getPosts();
    //so if you want to use the value of your http call outside.. 
    //..of the service here is a good place where to do subscribe()
     this.data.subscribe(data => {
       console.log(this.data;
    });
  
  }

  ngOnInit() {
  }

}

答案 2 :(得分:0)

尝试以下代码段。 您收到undefined,因为您在http请求之前分配数据可以解析值。从服务中删除订阅并将其移至组件。

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  private ROOT_URL = 'https://jsonplaceholder.typicode.com';

  constructor(private http: HttpClient) {}

  getPosts() {
    return this.http.get(`${this.ROOT_URL}/posts`);
  }

}

AppComponent.ts

import { Component } from '@angular/core';
import {DataService} from './data.service';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ] 
})
export class AppComponent  {
  constructor(public data:DataService){

    this.data.getPosts().subscribe(data=>{
      console.log(data);
    })
  }

}

请参阅此处的Demo

答案 3 :(得分:0)

您期望返回值并且不返回任何内容。你的return语句放在一个嵌套的lambda函数中,因此在你使用它的地方使用“return”会导致内部函数返回一个值,而不是你需要的外部函数。

我建议你阅读有关异步编程的内容,特别是Angular中的Observable(它与Promise的概念相同)。

答案 4 :(得分:0)

我基本同意@Eduardo Vargas的答案,但在解析器中执行此操作可能也是个好主意,它将调用api,并将数据放入路径快照中。由于这个原因,它不会在空页面上等待构造函数中的subscribe上的数据加载。更多信息:

https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html