我制作了一個用于管理資料庫的基本應用程式。資料顯示在表格和用于洗掉每個專案的按鈕中。出于某種原因,洗掉專案時,資料不會在第一次單擊按鈕時重繪 ,而是在第二次單擊時重繪 。第二次單擊該按鈕時,控制臺會為 http 請求輸出 404 錯誤,因為該專案不存在。
我想知道為什么資料在那之前沒有重新加載。這是我的組件:
import { Component, OnInit } from '@angular/core';
import { BackendService } from 'src/app/backend.service';
import { ICity } from '../interfaces/city';
import { ICountry } from '../interfaces/country';
@Component({
selector: 'app-cities',
templateUrl: './cities.component.html',
styleUrls: ['./cities.component.css']
})
export class CitiesComponent implements OnInit {
public countries: ICountry[] = [];
public cities: ICity[] = [];
constructor(private _backendService: BackendService) { }
ngOnInit(): void {
this.loadCities();
this.loadCountries();
}
loadCities() {
this._backendService.getCities().subscribe(data => {
this.cities = JSON.parse(JSON.stringify(data)).cities;
});
}
loadCountries() {
this._backendService.getCountries().subscribe(data => {
this.countries = JSON.parse(JSON.stringify(data)).countries;
});
}
submit(city: ICity) {
this.remove(city);
this.ngOnInit();
}
remove(city: ICity): void {
this.countries.forEach((cn) => {
if (cn.majorCities.find(c => c.name == city.name)) {
console.log(cn);
this._backendService.removeCity(cn.name.toLowerCase(), city.name.toLowerCase()).subscribe(data => console.log(data));
}
});
}
}
模板:
<h1>Cities</h1>
<tbody>
<tr>
<td><h3>City</h3></td>
<td><h3>Population</h3></td>
<td><h3>Area in km2</h3></td>
<td><h3>City Rank</h3></td>
</tr>
<tr *ngFor="let city of cities">
<td>{{ city.name }}</td>
<td>{{ city.population }}</td>
<td>{{ city.area }}</td>
<td>{{ city.rank }}</td>
<button type="button" (click)="submit(city)">Delete</button>
</tr>
</tbody>
uj5u.com熱心網友回復:
你可能在這里有一個競爭條件。您正在提交洗掉請求,但在收到和處理回應之前執行重繪 。使用 RxJS 訂閱時,您可以執行以下操作...
this._backendService.removeCity(cn.name.toLowerCase(), city.name.toLowerCase()).subscribe(
// This is the callback for when the response was successful.
// No error was caught during the request.
(data) => {
// You can attempt a refresh here because we know the request has
// completed and the row was deleted.
this.refresh();
},
// This is the callback for when the response was not successful.
// The backend service threw some sort of error, or the code ran into an error
// during execution. You can handle the error here (display some message).
(error) => {
// Do something in response to the error.
}
// This is the code to run when the Observable has communicated that it has
// completed. The observable has said "I'm done sending messages, there will be
// no more," so do whatever you need to in response to that.
() => {
// Do something...
}
);
我也不建議您使用ngOnInit重繪 操作,因為它是Angular 使用的保留方法;您可能會發現,通過呼叫ngOnInit,所做的事情比您想象的要多。
ngOnInit() {
this.refresh();
}
public refresh(): void {
// Your refresh logic here.
}
uj5u.com熱心網友回復:
需要Ellobartion。根據提供的ts,嘗試更新this.cities post洗掉呼叫服務agian而不是og ngOnInit
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408388.html
標籤:
