簡體   English   中英

Angular 5 - HttpClient服務 - 組件無法獲取數據

[英]Angular 5 - HttpClient Service - Component not getting data

我正在使用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'

我做錯了什么?

不要訂閱服務,返回observable並在組件上訂閱它。 因為它是異步的,所以組件上的數據變量將是未定義的,因為您在http請求可以解析值之前分配了該變量。

在服務上:

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

在共同作用:

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

 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() { } } 

請嘗試以下代碼段。 由於您在http請求可以解析值之前分配數據,因此undefined 從服務中刪除訂閱並將其移至組件。

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

}

在這里查看演示

您期望返回值並且不返回任何內容。 你的return語句放在一個嵌套的lambda函數中,因此在你使用它的地方使用“return”會導致內部函數返回一個值,而不是你需要的外部函數。

我建議你閱讀有關異步編程的內容,特別是關於Angular中的Observable(它與Promise的相同概念有效)。

我基本同意@Eduardo Vargas的答案,但在解析器中執行此操作可能也是個好主意,它將調用api,並將數據放入路徑快照中。 由於這個原因,它不會在空頁面上等待在構造函數中加載訂閱數據。 更多信息:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM