角度7。 我通过自己创建的服务进行了http调用,返回调用结果后,页面会自动刷新。我认为这种行为可能与Observable有关,但我不知道问题出在哪里
First way to call to http:
deleteBrand(brand: Brand) {
if (confirm("¿Estás seguro que deseas eliminar el registro?")) {
return this.http.delete(`http://localhost:3000/api/brand/${brand._id}`)
.subscribe(data => this.deleteElementFromBrands(brand))
}
}
private deleteElementFromBrands(brand: Brand) {
console.log(JSON.stringify(brand));
var i = this.findIndex(this.brands, brand);
this.brands.splice(i, 1);
}
private findIndex(array: any[], item: any): number {
var i = 0;
for (i; i < array.length; i++) {
if (array[i]._id == item._id) {
return i;
}
}
return -1;
}
此外,如果我使用其他代码,则会发生页面的自动刷新,这是不希望的
Call that refreshes the page unwanted:
// --- listbrands.component.ts
deleteBrand(brand: Brand) {
if (confirm("¿Estás seguro que deseas eliminar el registro?")) {
this.brandService.deleteBrand(brand._id)
.subscribe(
res =>
this.deleteElementFromBrands(brand)
);
}
}
//---- Y el servicio
//---- brandService.component.ts
deleteBrand (id: string): Observable<any> {
return this.http.delete(`${this.domain}${this.brandUrl}/${id}`)
.pipe(
tap(_ => console.log(`deleted item id=${id}`))
);
}
<div class="container">
<div class="row">
<div class="col-lg-3"></div>
<div class="col-lg-6">
<h2>Lista de Marcas de Aeronaves</h2>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Marca</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let brand of brands">
<td>
<a>
<img
src="../../../../assets/images/{{ brand._id }}.{{
brand.extension
}}"
alt="imagen"
class="card-img-top "
/>
</a>
</td>
<td>{{ brand.brand }}</td>
<td>
<div class="d-flex justify-content-end">
<a [routerLink]="['/brand/edit', brand._id]"
><i class="fa fa-edit fa-2x"></i
></a>
</div>
</td>
<td>
<div class="">
<i
class="fa fa-trash fa-2x"
(click)="this.deleteBrand(brand)"
style="cursor: pointer; color: tomato;"
></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<form class="link right-space">
<input
type="submit"
value="Nuevo"
class="btn btn-primary"
routerLink="/brands/new"
/>
</form>
</div>
<div class="col-lg-3"></div>
</div>
</div>
这里是后端代码
function deleteBrand(req, res) {
let brandId = req.params.brandId;
Brand.findById(brandId, (err, brand) => {
if (err)
return res.status(500).send({ message: `Error en la petición: ${err}` });
if (!brand)
return res.status(404).send({ message: `No se encuentra en la BD` });
brand.remove(err => {
if (err)
throw err;
else{
console.log(`Elemento borrado: ${brand}`);
// Borramos el archivo de imagen de la carpeta public
let oldFile = brandId + "." + brand.extension;
fs.unlink("./frontend/src/assets/images/" + oldFile, err => {
if (err)
throw err;
else{
console.log(`Imagen borrada`);
}
});
res.send({ message: `Elemento borrado: ${brand}`, brand });
}
});
});
}
答案 0 :(得分:1)
使用json服务器时,我遇到了同样的问题。
您应该将可以由服务器更改的文件保留在src /目录之外。否则,每次文件更改时,Angular都会刷新页面。
答案 1 :(得分:0)
将JSON文件(Fake JSON-server)移动到Angular项目之外。然后,当您运行它时,当看到文件更改时Angular不会自动编译,因此不会重新加载它。