我正在开发预算应用程序。我有一个组件,可以保存要传递给存储在其自己文件中的数组的值。我能够从数组中获取数据,但似乎无法弄清楚如何将数据推入数组。
有没有办法做到这一点,还是我必须创建另一个组件并将数组存储在该组件中?
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
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'
}]
}
];
答案 0 :(得分:1)
定义一个真正的基本服务来为您保存数据,这样您就可以将其注入所需的任何组件中并自由访问数据。
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
}
您可以在服务中定义用于添加到阵列或从阵列中删除的函数,以及在数据周围需要执行的其他任何操作。