Posted under Angular
Permalink
Tags Angular, Tip, Tutorial
A common pattern used in service layers is to make calls to an underlying repository or API, and then map the results to domain layer objects via mappers/convertors. Often, it may be necessary to make multiple repository calls and then combine them in the mapping phase to create the resulting domain object graph which is then returned. With traditional synchronous calls, e.g. to an underlying JPA repository, this is a straightforward exercise.
However, Angular 2 by default makes HTTP api call results available asynchronously as Observables, which poses an immediate issue with how to combine the results. I certainly did not want to embed Observables as properties within my domain objects, as I wanted the domain objects as POTOs (Plain Old Typescript Objects) and did not want to couple them/pollute them with Observables.
Handling the above pattern is in fact straightforward, but does involve a paradigm shift compared with imperative OO style programming as you need to get your head around reactive programming, in this case ReactiveX/RxJS which Angular uses.
- In this case we are using RxJs Observables for which the api is documented here.
- The available operators for use with Observables are documented here.
- ReactiveX/RxJs makes extensive use of Marble diagrams an example of which may be found here.
- Another useful introduction site to RxJS may be found here.
Note that it is possible to convert the observables to promises and use promise chaining to achieve similar results. However, I decided to stick with observables as the majority of comments online such as this post indicate that observables can do all that promises can, and more, and they are the default/chosen direction for Angular 2. It felt counter intuitive to have to convert the observables to promises all the time when there was no real need – whilst and to do so appeared to go against the chosen way forward for Angular 2.
My first prototype needed to combine 2 API calls, and for this I used the combineLatest instance method. (This is called on one Observable and allows one or more other observables to be combined with it. There is also a static method available on the Observable class.) I found this solution in this StackOverflow post. These methods do do the following :-
- Combine 2 or more observables and emits a single output observable
- Before the output observable emits an item, all of the input observables must have emitted at least one item
- Once all the observables have emitted something, the output emits an output item.
- It continues to emit items whenever any of the input observables emit another item.
- Note that in our case, multiple emits for an observable do not occur. Whilst we are using observables, each one will only emit a single output item in our case, when the HTTP call completes.
- Note that per the example code below, I use lambdas (=> operator) routinely. The lambda used on the return of combineLatest will be called when the output observable emits an item (i.e. when both the HTTP calls have completed). The other lambdas are just used for standard synchronous filter/map/reduce operations on the arrays – these are standard in Javascript and hence Typescript, so they are not asynchronous/using observables.
For the requirement of my original pattern, i.e. make a number of repository calls, then map them all to a domain object graph, the above approach works fine. Note that there are a number of other operators on observables which are quite nuanced and this example just scratches the surface of Reactive programming, but in my experience the above is a very common pattern. Some of the other operators/methods distinguish between emits on an observable and the observable actually closing. As in the above case we just get one emit from each, we don’t need to get into that issue.
An outline example from my prototype code follows (imports and domain objects omitted for clarity). Note that it is just a prototype and a number of issues have not been properly addressed yet (such as externalisation of configuration data such as API urls):-
places-service.ts
@Injectable()
export class PlacesService {
static apiBase: string = 'http://localhost:5984/places-guide/';
static apiGetByLocationName: string = `${PlacesService.apiBase}_design/places/_view/placesByLocationName?include_docs=true`;
static apiGetFeatures: string = `${PlacesService.apiBase}_design/places/_view/featuresByOrdinal?include_docs=true`;
constructor(private http: Http, private featureMapper: FeatureMapper, private placeMapper: PlaceMapper) {}
fetch(): Observable<Place[]> {
return this.http.get(PlacesService.apiGetByLocationName)//The lambda here is called when the output observable emits an item (which only happens once when both HTTP calls complete).
.combineLatest(this.http.get(PlacesService.apiGetFeatures), (placesRows, featuresRows) => {
let features: Feature[] = this.featureMapper.mapAll(featuresRows.json().rows);
let places: Place[] = this.placeMapper.mapAll(placesRows.json().rows, features, PlacesService.apiBase);
return places;
});
}
}
place-mapper.ts
@Injectable()
export class PlaceMapper {
constructor(private placeFeaturesMapper: PlaceFeaturesMapper) {};
public map(row: any, placeFeatures: PlaceFeatures, apiBase: string): Place {
let place: Place = Place.create(
row.id,
row.doc.name,
row.doc.strapline,
row.doc.description,
Address.create(
row.doc.address.address1,
row.doc.address.locality,
row.doc.address.postTown,
row.doc.address.postCode),
row.doc.lat,
row.doc.long,
row.doc.website,
row.doc.phone,
row.doc.email,
placeFeatures,
apiBase + row.doc._id + "/thumbnail.jpg",
apiBase + row.doc._id + "/detail.jpg"
);
return place;
}
public mapAll(rows: any[], features: Feature[], apiBase: string){
let placesPlaceFeaturesMap: {[key: string]: PlaceFeatures } = this.createPlacesPlaceFeaturesMap(rows, features);
return rows//this is standard array filtering and mapping with lambdas
.filter(row => row.doc.type == 'place')
.map(row => this.map(row, placesPlaceFeaturesMap[row.doc.placeFeaturesId], apiBase));
}
createPlacesPlaceFeaturesMap(rows: any[], features: Feature[]): {[key: string]: PlaceFeatures } {
let placesPlaceFeaturesMap: {[key: string]: PlaceFeatures } =
rows.filter(row => row.doc.type == 'placeFeatures')//This is a standard array lambda. Reduce is used as we are populating a single return object..reduce((map, row) => {
map[row.doc._id] = this.placeFeaturesMapper.map(row, features);
return map;//Note that the {} is the seed/initial value for the reduce, where we initialise the empty output object
}, {});
return placesPlaceFeaturesMap;
}
}
place-features-mapper.ts@Injectable()
export class PlaceFeaturesMapper {
public map(row: any, features: Feature[]): PlaceFeatures {
let list: PlaceFeature[] = this.buildList(row.doc._id, row.doc.placeFeatures, features );
let map: {[key: string]: PlaceFeature} = this.buildMap(list);
return PlaceFeatures.create(row.doc._id, list, map, features);
}buildList(placeFeaturesId: string,
rawPlaceFeatures: {[key: string]: {rating: number} },
features: Feature[]): PlaceFeature[] {
let placeFeatures: PlaceFeature[] = features
.filter(feature => rawPlaceFeatures[feature.id])
.map(feature => PlaceFeature.create(
placeFeaturesId,
feature.id,
feature.ordinal,
feature.name,
feature.description,
feature.searchable,
feature.rateable,
rawPlaceFeatures[feature.id].rating)
);
return placeFeatures;
}buildMap(placeFeatures: PlaceFeature[]): {[key: string]: PlaceFeature} {
let placeFeaturesMap: {[key: string]: PlaceFeature} =
placeFeatures.reduce((map, placeFeature) => {
map[placeFeature.featureId] = placeFeature;
return map;
}, {});
return placeFeaturesMap;
}
}feature-mapper.ts@Injectable()
export class FeatureMapper extends AbstractMapper<any, Feature> {
public map(row: any): Feature {
let feature: Feature = Feature.create(
row.id,
row.doc.ordinal,
row.doc.name,
row.doc.description,
row.doc.searchable,
row.doc.rateable);
return feature;
}
}abstract-mapper.tsexport abstract class AbstractMapper<R,T> {
public abstract map(row: R): T;
public mapAll(rows: R[]): T[] {
return rows.map(row => { return this.map(row);});
}
}
Leave a Reply
You must be logged in to post a comment.