1

我在理解如何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
        });
  }
}

任务组件.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 对象?

4

1 回答 1

4

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

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

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

ngOnInit() {
  this.apiService.getAllTasks()
  .subscribe( data => {
    //now you have the data
  })
}
于 2017-11-06T16:13:27.413 回答