簡體   English   中英

如何避免為不同的組件編寫相同的 http 訂閱塊?

[英]How to avoid writing same http subscribe blocks for different components?

讓我們假設有一個服務將用於 http 請求調用。兩個不同的組件(可能超過兩個)將通過該服務使用相同的 observables 發送相同的請求。在得到應該分配給全局變量的結果后(組件沒有父子或子父的關系)。下面我為所有組件編寫了相同的代碼塊。有沒有更好的方法來編寫這個 function 並通過返回相同的值來調用?

服務

  getStudents() {
    const requestUrl = this.apiUrl + 'students/';
    return this.httpClient.get(requestUrl);
  }

組件1

  studentList:Student[]=[];
  getStudents.subscribe((students:Student[])=>{
      this.studentList=students;
      //Some operations
  })

組件2

  studentList:Student[]=[];
  getStudents.subscribe((students:Student[])=>{
       //Some operations 
  this.studentList=students;
  })

我不是全局 state 的粉絲,但是如果您想使用全局 state 跨組件維護相同的學生列表,那么 state 可以單獨存在於每個組件中而不是存在於服務中

因此,例如:

服務


studentList:Student[] = [];

setStudents(students:Student[]) {
  this.studentList = students;
  // Operations involved with setting students
}

updateStudents() {
  const requestUrl = this.apiUrl + 'students/';
  return this.httpClient.get(requestUrl).pipe(
    tap(this.setStudents)
  );
}

零件

ngOnInit(){
  this.service.updateStudents().subscribe();
}

你可以在你的服務中擁有一個 Observable,

studentsReceived:Subject = new Subject();

getStudent() 成功后,您可以發出下一個 studentReceived 值。

現在您可以訂閱學生在您的組件中收到的內容,在成功調用 API 后,您將收到每個訂閱的組件的通知。

studentRecived.subscribe(data=>{ // do some code })

您必須在 AppComponent 等更高級別的組件上調用此 getStudent()。

2 這里重要的事情:

1) If you dont want to repeat the same block of code, then create a method in the service file, 
and call it in the component. Something like this: 

SERVICE: 

makeSubcription(componentVariableName) {
  this.yourObservable.subcribe(subscribedValue => {
     componentVariableName = subscribedValue;
  })
}

In your Component, you can do this: 

yourComponentMethod() {
  this.service.makeSubscription(this.studentLists);
}


************

2) If you dont want to make a service call too many times, what you can do is, 
use Behavior Subject and try to store the values, so that you are subscribing to the observable and not the actual API call. Something like this: 


private initialValuesForObservable: YourObjectModel = {}; // or null;

private observableSource: BehaviorSubject<YourObjectModel> = 
  new BehaviorSubject<YourObjectModel>(this.initialValuesForObservable);

public subscribableObservable: Observable<YourObjectModel> = 
  this.observableSource.asObservable();


setObservableValue(data: YourObjectModel) {
  this.observableSource.next(data);
}

getObservableData() {
  return this.subscribableObservable;
}



In your COMPONENT; 

this.service.getObservableData().subscribe(latestObservableData => {
  this.schoolList = latestObservableData;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM