我在将 ID 属性分配给某些 HTML 按钮时遇到问题。
categories.service.ts:
getCategories(): Observable<Category[]> {
let headers = new Headers({ 'Authorization': this.authenticationService.token });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.categoriesURL, options)
.map((response: Response) => response.json());
}
categories.component.ts:
import { Component, OnInit } from '@angular/core';
import { Category } from '../../_models/category';
import { CategoriesService } from '../../_services/categories.service';
@Component({
selector: 'app-categories',
templateUrl: './categories.component.html',
styleUrls: ['./categories.component.css']
})
export class CategoriesList implements OnInit {
categories: Category[] = [];
constructor(private categoriesService: CategoriesService) { }
ngOnInit() {
// Limpia el mode
this.categoriesService.clearMode();
// Lista de categorías
this.categoriesService.getCategories()
.subscribe(categories => {
this.categories = categories;
});
}
setMode(event){
this.categoriesService.setMode(event.target["name"], event.target["id"]);
}
}
categories.component.html:
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="content">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Nombre</th>
<th>Descripción</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let category of categories">
<td>{{category.name}}</td>
<td>{{category.description}}</td>
<td><button (click)="setMode($event)" routerLink="/categories/form" type="button" name="editando" id="{{category.id}}" class="btn btn-info"><i class="ti-pencil-alt"></i> Editar</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
说明: 当加载“/categories”时,触发从服务器检索数据的 getCategories() 函数。然后它在 View 中填充我的表,并使用一个编辑按钮构建每一行,最后将类别 ID 作为按钮 ID。我正在做的是当用户单击编辑按钮时,触发 categories.component.ts 中的 setMode() 函数并检索按钮 ID 并将模式和 ID 保存在服务中。查看编辑表单时会用到这个模式(因为我用它来创建和编辑同一个资源) ID 会被用来向服务器请求资源。
错误:有时,当我点击编辑按钮时,它会导航到表单,但不会调用服务器来检索资源(我检查了 Chrome 中的网络选项卡)。我在 setMode() 函数中记录了 ID,并注意到有时它是未定义的,所以我认为我的问题不在表单中。它是随机发生的,有时我点击编辑按钮 5 次,它起作用了,下一次给了我未定义的,有时或多或少。所以我认为这可能与我的要求有关,但我不确定。
我已经尝试过的:
- 将 Observable 更改为 Promise
- 在数据出现之前不呈现列表 从服务器检索(使用 Observable 和 Promise)
最佳答案
您应该更改您的 setMode()
方法,以便它发送参数而不是事件,这样会更容易管理。
setMode(mode, category_id)
如果导航似乎出现在您的代码执行之前,您应该在 setMode()
的末尾使用 this.router.navigate([...])
进行导航> 方法。
关于javascript - 使用 Angular 2 动态分配 HTML 按钮 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45579222/