【发布时间】:2021-09-16 22:28:35
【问题描述】:
我是 Angular 的新手,正在尝试使用日期过滤器做应用程序。所以这是我的问题:
我正在尝试将任务发送到服务以从另一个组件接收。当我从我的服务运行 getTasks 模块时,它不会返回我的数组。控制台只显示函数。
import { Injectable } from '@angular/core';
import { NewTaskPageComponent, ToDoTask } from './new-task-page/new-task-page.component';
import { task } from './app.component';
@Injectable({
providedIn: 'root'
})
export class TaskService {
tasks:ToDoTask[]=[];
constructor() { }
addTask(task:ToDoTask){
this.tasks.push(task);
}
getTasks():ToDoTask[]{
return this.tasks;
}
}
这是我的服务.ts
import {AppComponent} from '../app.component';
import { Component, OnInit } from '@angular/core';
import { TaskService } from '../task.service';
@Component({
selector: 'app-new-task-page',
templateUrl: './new-task-page.component.html',
styleUrls: ['./new-task-page.component.sass'],
providers: [TaskService]
})
export class NewTaskPageComponent implements OnInit {
newTask ?: ToDoTask;
constructor(private _taskService:TaskService){
}
ngOnInit(): void {
}
sendTask(task:string,date:string): void{
this.newTask = new ToDoTask(task,date);
this._taskService.addTask(this.newTask);
console.log(this._taskService.getTasks);
}
}
export class ToDoTask{
task: string;
date: string;
constructor(task:string,date:string){
this.task = task;
this.date = date;
}
}
这是我正在尝试发送和获取数据的组件。
【问题讨论】:
-
将
console.log(this._taskService.getTasks)替换为console.log(this._taskService.getTasks())。由于 getTasks 是您需要调用它的服务的方法。
标签: angular service components