Angular 5:httpClient 未返回 JSON

Angular 5: httpClient is not returning JSON

我无法理解 HttpClient 的工作原理

api.service.js

import {Injectable} from '@angular/core';
import {environment} from '../../environments/environment';
import {HttpClient} from '@angular/common/http';
import {Task} from './task';
import 'rxjs/add/operator/map';

const API_URL = environment.apiUrl;

interface JSONObject {
  _id: string;
  title: string;
  created_at: string;
  startTime: string;
  endTime: string;
  state: boolean;
  description: string;
}

@Injectable()
export class ApiService {
  public tasks;

  constructor(private http: HttpClient) {
  }

  public getAllTasks() {
    return this.http
      .get<JSONObject>(API_URL + '/api/task').subscribe(
        data => {
          this.tasks = data;
          console.log(data); //Returning Array
        });
  }
}

task.component.ts

import {Component, OnInit} from '@angular/core';
import {ApiService} from './api.service';
import {Subscription} from 'rxjs/Subscription';

@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  styleUrls: ['./task.component.css'],
  providers: [ApiService]
})
export class TaskComponent implements OnInit {

  constructor(private apiService: ApiService) {

  }

  ngOnInit() {
    console.log(this.apiService.tasks); // <<< Not Returning JSON :(
  }

  getAllTasks() {
    return this.apiService.getAllTasks();
  }
}

我是 Angular 5 的新手,必须为课程创建一个 CRUD 应用程序,但实际上遇到了这个问题。

如何在 task.component.ts 中获取 JSON 对象?

不要订阅服务中的可观察对象,也不要在其中存储值。将方法更改为:

public getAllTasks() {
  return this.http.get<JSONObject>(API_URL + '/api/task')
}

因此您的服务专门用于处理 API 请求。 然后在你的组件中:

ngOnInit() {
  this.apiService.getAllTasks()
  .subscribe( data => {
    //now you have the data
  })
}