最佳答案
我想删除一个项目从一个存储的数组在角度2,与类型脚本。我正在使用一个名为 数据服务,theDataService 代码的服务:
export class DataService {
private data: string[] = [];
addData(msg: string) {
this.data.push(msg);
}
getData() {
return this.data;
}
deleteMsg(msg: string) {
delete [this.data.indexOf(msg)];
}
}
还有我的组件类:
import {Component} from '@angular/core'
import {LogService} from './log.service'
import {DataService} from './data.service'
@Component({
selector: 'tests',
template:
`
<div class="container">
<h2>Testing Component</h2>
<div class="row">
<input type="text" placeholder="log meassage" #logo>
<button class="btn btn-md btn-primary" (click)="logM(logo.value)">log</button>
<button class="btn btn-md btn-success" (click)="store(logo.value)">store</button>
<button class="btn btn-md btn-danger" (click)="send()">send</button>
<button class="btn btn-md " (click)="show()">Show Storage</button>
<button (click)="logarray()">log array</button>
</div>
<div class="col-xs-12">
<ul class="list-group">
<li *ngFor="let item of items" class="list-group-item" #ival>
{{item}}
<button class="pull-right btn btn-sm btn-warning" (click)="deleteItem(ival.value)">Delete
</button>
</li>
</ul>
</div>
<h3>{{value}}</h3>
<br>
</div>
`
})
export class TestsComponent {
items: string[] = [];
constructor(
private logService: LogService,
private dataService: DataService) {
}
logM(message: string) {
this.logService.WriteToLog(message);
}
store(message: string) {
this.dataService.addData(message);
}
send(message: string) {
}
show() {
this.items = this.dataService.getData();
}
deleteItem(message: string) {
this.dataService.deleteMsg(message);
}
logarray() {
this.logService.WriteToLog(this.items.toString());
}
}
现在,除了我试图删除一个项目之外,一切都正常。日志显示该项仍然在数组中,因此仍然显示在页面上。如何删除项目后,我选择了它与删除按钮?