[英]How do I pass data from a component to a .ts file holding my array?
我正在开发一个预算应用程序。 我有一个组件,其中包含我想传递给存储在它自己的文件中的数组的值。 我能够从数组中获取数据,但我似乎无法弄清楚如何将数据推送到数组中。
有没有办法做到这一点,还是我必须创建另一个组件并将数组存储在该组件中?
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');
}
}
模拟用户.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'
}]
}
];
定义一个真正为您保存数据的基本服务,这样您就可以将其注入到您需要的任何组件中并自由访问数据。
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'
}]
}];
}
}
在您的一个组件中,您可以像这样访问数据。
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
}
您可以在服务中定义用于添加到数组和从数组中删除的函数,以及您需要围绕数据执行的任何其他操作。
角度文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.