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