gpt4 book ai didi

javascript - 从 Angular 2 中的存储数组中删除项目

转载 作者:太空狗 更新时间:2023-10-29 16:45:24 26 4
gpt4 key购买 nike

我想使用 Type Script 从 Angular 2 中的存储数组中删除一个项目。我正在使用名为Data Service 的服务,DataService 代码:

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());
}
}

现在,一切正常,除了我尝试删除项目时。日志显示该项目仍在数组中,因此仍显示在页面上。如何在使用删除按钮选择项目后将其删除?

最佳答案

您不能使用delete 从数组中删除一个项目。这仅用于从对象中删除属性。

你应该使用 splice从数组中删除一个元素:

deleteMsg(msg:string) {
const index: number = this.data.indexOf(msg);
if (index !== -1) {
this.data.splice(index, 1);
}
}

关于javascript - 从 Angular 2 中的存储数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40462369/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com