[英]How to organize Angular data service
我對可觀察對象,觀察者,主題,BehaviorSubject,服務,注入等感到有些困惑。
我正在嘗試制作一個簡單的財務應用程序。 我有一個事務處理服務,可以從REST服務器獲取數據,然后將其提供給其他服務,如果需要,可以對其進行更新。 我可以獲取列表事務組件(該組件從getTransactions()
獲取其數據)以通過服務進行更新,但是我不知道如何獲取編輯組件(該組件從“ getTransaction(id)
”獲取其數據getTransaction(id)
來工作。
讓組件使用整個數組中的數據(讀/寫訪問)以及只想使用數組中單個元素的組件的最佳方法是什么?
這是我現在所擁有的:(我已對其進行了很多更改,因此它目前已損壞,但是您可以看到我在做什么)
export class DataBrokerService {
public transactions:Transaction[];
constructor() {}
ngOnInit(){
}
getTransactions(): Observable<Transaction[]>{
if (needUpdate){
// Download from REST API, subscribe result to transactions
this.updateTransactions();
}
return of(this.transactions);
}
getTransaction(id:number): Observable <Transaction>{
let transaction:Transaction;
this.getTransactions().subscribe(txns => transaction = txns.find(txn => txn.id === id))
});
return transaction$;
}
我也做了這個演示,展示了我要去的東西: https : //stackblitz.com/edit/angular-stackblitz-demo-dftmn3
這是來自以下問題的后續問題: 從可觀察數組中獲取一個值
這是一個好問題。 我知道剛開始使用RxJ會讓人感到困惑,但是當您掌握了它時,它就非常強大。
您想要的可以通過BehaviorSubject
實現。
讓我們找出Subject
是什么,然后進入BehaviorSubject
Subject:等效於EventEmitter,並且是將值或事件多播到多個觀察者的唯一方法
欲了解更多信息,請看這里
因此,我們知道Subject
就像EventEmitter
。 當有人訂閱它時,每當您調用subject.next(value)
,每個訂閱者都會獲得新值。 但是,較晚的訂閱者(意味着在調用next
方法后訂閱Subject
)將無法獲得先前的值。 這是BehaviorSubject
進入場景的地方。
就像Subject
一樣,但是當新的訂閱者訂閱它時,它將發出以前的值。 讓我們在您的代碼中使用它。
export class DataBrokerService {
// do not expose your subject to other classes
private _transactions$: BehaviorSubject<Transaction[]> = new BehaviorSubject([]);
// instead provide it as an observable
public readonly transactions: Observable<Transaction[]> = this._transactions$.asObservable();
needUpdate = true;
constructor(private http: HttpClient) { }
ngOnInit() {
}
// just return the observable
getTransactions(): Observable<Transaction[]> {
if (needUpdate) {
this.updateTransactions();
}
return this.transactions;
}
// you can iterate over your transactions and filter them,
// but DO NOT ever subscribe to it within a service.
// Otherwise, other classes won't be able to retrieve the value.
getTransaction(id: number): Observable<Transaction> {
return this.getTransactions().pipe(
map(txns => txns.find(txn => txn.id === id))
);
}
// when you need to update the transactions,
// simply call this method
updateTransactions() {
this.http.get('transactions').subscribe(txns => {
this.needUpdate = false;
this._transactions$.next(txns);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.