【问题标题】:Angular 5: httpClient is not returning JSONAngular 5:httpClient 不返回 JSON
【发布时间】:2018-05-09 10:43:40
【问题描述】:

我在理解 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 对象?

【问题讨论】:

  • 答案有帮助吗

标签: angular angular5


【解决方案1】:

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

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

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

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

【讨论】:

  • 谢谢!这就像一个魅力。所以最好不要在服务中存储数据?我有很多东西要学 Angular..
  • 您可以将它们存储在服务中,但最好的方法是 IMO 使用 EventEmitter (angular.io/api/core/EventEmitter) 向订阅的侦听器(在组件中)“广播”值已更改。基本上,组件订阅 observable,当服务的值发生变化时发出值。
猜你喜欢
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
相关资源
最近更新 更多