问题描述
更改列表后,我想在# data into list
filename = 'API_SP.DYN.TFRT.IN_DS2_en_csv_v2_1622869.csv'
with open(filename,encoding='utf-8-sig') as f:
reader = csv.DictReader(f)
next(reader)
next(reader)
for row in reader:
country_name = row['Data Source']
# '.strip() or 0' part used to ensure fertility data can be read into fertility without
# error caused by blank '' strings in the data.
# Has to be 'row[None]' to avoid KeyError
fertility = float(row[None][-4].strip() or 0)
code = get_country_code(country_name)
if code:
print(code + ': ' + str(fertility))
else:
print('ERROR - ' + country_name)
# build dictionary of population data
fertility_2018_data = {}
for row in reader:
country_name = row['Data Source']
fertility = float(row[None][-4].strip() or 0)
code = get_country_code(country_name)
if code:
fertility_2018_data[code] = fertility
中重新加载列表。该列表作为component
存储在service
中。我在组件中订阅了主题,并在表格中显示了列表。当用户单击列表中的项目时,它将通过BehavIoUrSubject
打开视图。用户可以在此处执行此项目的某些操作(删除,编辑/保存等),但是删除某项目后,它的确会将其删除在router
的原始列表中,但仍会在显示列表的组件。我以为如果进行更改并重新加载列表,将检查行为主题,但似乎不起作用。
我的service
:
service.ts
我的export class OfferService {
offers: Offer[] = [];
public offeRSSubject = new BehaviorSubject<Offer[]>(this.offers);
constructor(private http: HttpClient) {
this.generaterandomOffers();
}
private generaterandomOffers(): void {
for (let i = 0; i < 8; i++) {
let offer = new Offer(this.offeRSSubject.getValue().length + 1);
offer = Offer.createrandomOffer();
this.offeRSSubject.getValue().push(offer);
}
}
public FindAll(): Offer[] {
return this.offeRSSubject.getValue();
}
// observable of offers list
public getAll(): Observable<Offer[]> {
return of(this.offeRSSubject.getValue());
}
public FindById(offerId: number): Offer {
return this.offeRSSubject.getValue().find(o => o.id === offerId);
}
public Save(offer: Offer): Offer {
let offerExist = false;
const index = this.offeRSSubject.getValue().findindex(o => o.id === offer.id);
this.offeRSSubject.getValue().forEach( element => {
if (element.id === offer.id)
{
element = offer;
offerExist = true;
this.offeRSSubject.getValue()[index] = element;
}
});
if (!offerExist)
{
this.offeRSSubject.getValue().push(offer);
}
return this.offeRSSubject.getValue().find(o => o.id === offer.id);
}
public DeleteById(offerId: number): Offer {
const deleteOffer = this.offeRSSubject.getValue().find(o => o.id === offerId);
this.offers = this.offeRSSubject.getValue().filter(o => o.id !== offerId);
this.offeRSSubject.next(this.offers);
return deleteOffer;
}
public AddOffer(): void {
let offer = new Offer(this.offers.length + 1);
offer = Offer.createrandomOffer();
this.offeRSSubject.getValue().push(offer);
}
}
(显示列表的地方):
Component.ts
解决方法
要连续从流中接收数据,您需要提供相同的参考。在服务getOffer方法中,您需要返回this.offersSubject.asObservable();
,这是同一流的只读部分。当您要更新流时,请在原始流上调用next。我已经创建了一些简单的demo! :)