[英]How do I pass data from a component to a .ts file holding my array?
I'm working on a budgeting app.我正在开发一个预算应用程序。 I have a component that holds values I would like to pass to an array that is stored in it's own file.
我有一个组件,其中包含我想传递给存储在它自己的文件中的数组的值。 I am able to get data from the array but I can't seem to figure out how to push data into the array.
我能够从数组中获取数据,但我似乎无法弄清楚如何将数据推送到数组中。
Is there a way to even do this or would I have to create another component and store the array in that component?有没有办法做到这一点,还是我必须创建另一个组件并将数组存储在该组件中?
input.component.ts input.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { USERS } from '../mock-users';
import { Users } from '../Users';
//import { Users } from '../Users';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
@Input() description: string;
@Input() date: Date;
@Input() amount: number;
@Input() category: string;
constructor() { }
ngOnInit() {
}
addExpense() {
console.log('expense added');
}
}
mock-users.ts模拟用户.ts
import { Users } from './Users';
export const USERS: Users[] = [
{
id: 1,
name: 'Keenan',
username: 'keenan.kaufman',
password: 'admin',
expenses: [{
//var myDate = new Date('2019-5-2T00:00:00');
date: new Date('2019-5-2T00:00:00'),
description: 'Electric Bill',
amount: 42,
category: 'Utilites'
},
{
date: new Date('2019-5-2T00:00:00'),
description: 'Rent',
amount: 350,
category: 'Rent'
}]
}
];
Define a really basic service that hold the data for you, this way you can inject it into any component you need and freely access the data.定义一个真正为您保存数据的基本服务,这样您就可以将其注入到您需要的任何组件中并自由访问数据。
import { Injectable } from '@angular/core';
@Injectable(
{
providedIn: 'root'
}
)
export class DataService{
constructor() { }
public users : Users[] = [
{
id: 1,
name: 'Keenan',
username: 'keenan.kaufman',
password: 'admin',
expenses: [{
//var myDate = new Date('2019-5-2T00:00:00');
date: new Date('2019-5-2T00:00:00'),
description: 'Electric Bill',
amount: 42,
category: 'Utilites'
},
{
date: new Date('2019-5-2T00:00:00'),
description: 'Rent',
amount: 350,
category: 'Rent'
}]
}];
}
}
In one of your components you can then access the data like so.在您的一个组件中,您可以像这样访问数据。
public usersLocal: Users[];
constructor(private dataService: DataService) {}
public ngOnInit(): void
{
this.usersLocal = this.dataService.users;
console.log(this.usersLocal);
// array held in service by reference can now push and / splice etc
}
You could define functions in the service for adding to and removing from the array, and any other actions you require surrounding the data.您可以在服务中定义用于添加到数组和从数组中删除的函数,以及您需要围绕数据执行的任何其他操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.