typescript - 如何在 Typescript 中定义数组的数量
问题描述
我需要从数组中删除值。但我无法确定这个数字。我在后端发送一个带有 id 的 DELETE 请求,但是如何在 TypeScript 数组中找到这个值。
数组Click示例
我的代码打字稿
export class FileService {
public myResults: string[];
public id: number;
Url: string = "";
constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string,
public dialog: MatDialog ) {
http.get<string[]>(baseUrl + '/getAllFiles').subscribe(result => {
this.myResults = result;
console.log(result);
}, error => { console.log('an error occured!'); console.log(error); });
this.Url = baseUrl;
}
public fileDelete(id) {
return this.http.delete(this.Url + '/delete' + id).subscribe(
data => {
console.log("DELETE Request is successful ", data);
const index = this.myResults.indexOf(id)
this.myResults.splice(index, 1);
},
我的 HTML 代码
<tr *ngFor="let myResult of myResults;">
<td>{{ myResult.idPres }}</td>
<td> {{ myResult.namePres }} </td>
<td><button type="button" id="delete" class="btn btn-danger" (click)="fileDelete(myResult.idPres)">Delete</button></td>
</tr>
解决方案
Array.prototype.indexOf
这样做是不够的。
您需要使用Array.prototype.findIndex:
public fileDelete(id) {
return this.http.delete(this.Url + '/delete' + id).subscribe(
data => {
console.log("DELETE Request is successful ", data);
// objArray is an array containing what we see in your screenShot
const obj = this.objArray.find(result=> result.idPres === id);
const fileName = obj.namePres;
// now fileName is a string so it's safe to find it in a string array with indexOf
const index = this.myResult.indexOf(fileName);
this.myResults.splice(index, 1);
},
推荐阅读
- apache-kafka - 为什么 kafka-console-consumer 在少量消息上超时?
- javascript - 如何对 graphql 解析器实施保护
- visual-c++ - 如何使用适用于所有工作区的 Microsoft C++ 编译器配置 VS Code?
- python - 使用 Pyinstaller 编译为 exe 的 Pywinauto 脚本在本地执行,但不使用 PSEXEC 从 cmd 行远程执行
- java - 设置 JFrame 中可见空间的大小
- c# - 我想将一个 int "index" 参数传递给一个方法对话框,并要求用户输入一个他要搜索的特定值的字符串
- c++ - std::initializer_list 构造函数导致编译器错误 C3202、C2661 和 C2976
- python - 小户型项目
- c++ - 根据索引值提取特定字节
- c - C、Linux中不同进程的线程同步