在Angular中,可以通过使用push()
方法将一个服务数组与自身进行推送。以下是一个示例解决方法:
首先,在你的服务中创建一个数组并导出它:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
data: any[] = [];
constructor() { }
}
然后,在你的组件中注入该服务,并使用push()
方法将数组与自身进行推送:
import { Component } from '@angular/core';
import { DataService } from 'path/to/data.service';
@Component({
selector: 'app-example',
template: `
- {{ item }}
`
})
export class ExampleComponent {
constructor(public dataService: DataService) { }
pushData() {
this.dataService.data.push('New Item');
}
}
在这个示例中,我们在ExampleComponent
中注入了DataService
,并使用pushData()
方法将'New Item'
推送到dataService.data
数组中。然后,在模板中使用*ngFor
指令遍历dataService.data
数组来显示所有的项目。
请注意,在这个例子中,我们假设DataService
已经被正确地注入并在模块中进行了正确的提供。