【问题标题】:Angular services doesn't show object array value [duplicate]角度服务不显示对象数组值[重复]
【发布时间】: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


【解决方案1】:

感谢a comment by vadimk7,我通过在函数周围添加括号解决了这个问题。

我将原始代码中的console.log(this._taskService.getTasks) 替换为console.log(this._taskService.getTasks())

尾括号是必需的,因为getTasks 是在服务上调用的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2018-07-10
    • 2018-03-20
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多