Good evening!
I'm currently working with Angular and rxjs, but I have a feeling that TypeScript is going to play a significant role in my project today. I've been exploring different methods to achieve my goal, but it's definitely challenging without the actual code at hand. Please bear with me as we imagine its functionality together.
My task involves fetching data from multiple endpoints, each providing a unique dataset for analysis.
getDataA(): Observable<DataTypeA> {
return get<DataTypeA>httpRequestUrl
.catchError((error) => return <HttpErrorType>)
}
getDataB(): Observable<DataTypeB> {
return get<DataTypeB>httpRequestUrl
.catchError((error) => return <HttpErrorType>)
}
getBothDataSets(): Observable<CombinedDataModel> {
zip(getDataA, getDataB).pipe(map([dataA, dataB]) => new CombinedDataModel(dataA, dataB))
Through the use of rxjs's zip function, I can combine the results from all endpoints into a new CombinedDataModel.
interface ICombinedData {
dataA: DataTypeA | HttpErrorType
dataB: DataTypeB | HttpErrorType
}
class CombinedDataModel {
dataA: DataTypeA | HttpErrorType
dataB: DataTypeB | HttpErrorType
constructor(dataA, dataB) {
this.dataA = dataA
this.dataB = dataB
additional functions()
}
}
Now comes the question - how do we safely handle the types of dataA and dataB respectively? There are several approaches I could consider.
An example like if (dataA.status) might be sufficient.
Assigning all error types a common Error field could also provide clarity in error handling.
Extending the Observable class to include an error field is another potential solution.
However, my preference would be to utilize a TypeOf function or perhaps an isError function for added type safety. While these patterns may not be widespread, I am eager to explore their benefits for a more robust implementation.