Implementing a Middle Tier in Angular 2+: Should I and How Should I?

In the app I am making, I rely on a third-party source of data. I need to apply some business rules and compose new objects with a combination of data from my own api and the third party api.

Again drawing from my experience with desktop apps and repositories of data retrieved from many services, I concluded that a middle tier was just the ticket. If I had not needed third party data, I would simply have my own api. But by inserting the middle tier I have set things up so that future apps that have little or no relationship with this app will be able to use the same middle tier.

Most likely established patterns exist for the type of thing I’m doing, but I couldn’t easily find them. So I had to invent my own.

The chief goals:

  1. Support data transfer to and from 2 or more apis.
  2. Support application levels. (free vs paid vs advanced, for example).
  3. Have no knowledge of a data repository such as a database or file system.

The diagram below shows the end result.  I felt free to name things in a way that made sense to me, based on the concept of space travel, with the APIs being the planets in outer space. Note– Since TypeScript now supports abstract classes, the shuttle classes that correspond to each level of the app can simply be extended. (click to enlarge).


Mapping Objects in Angular 2+

TLDR: skip to the end if you just want to see my solution


Back in the days of madness and C# programs, we used a library called Automapper.  We loved it and hated it.  It was used correctly and incorrectly.  Folks new to the team grasped their hair as if to pull it out (bald men were relegated to imaginary hair) and screamed.

Truthfully, Automapper is a fine library when used correctly.  Its purpose is to take one object and convert it into another with as few lines of codes as possible.  For example, you might receive an object from an api or a middle tier/business layer.  It has some properties useful to the client, and some that are not.  The corresponding client object(s) might have additional properties useful to the client.

It gets really boring to write code to convert one object to another, and for this reason Automapper exists.

automapper-ts and other approaches to solve mapping

In my current Angular 2+ project, I have a need to map objects coming from outside the client to client models, and client models to client view models, and the reverse.  I tried things.  Which things?

Before we talk about that, let me say that searching for mapping solutions most of the time brought up information on array mapping.  That’s a different thing.  The map function there applies a specified function to each element of an array– not what I am talking about here.

I remembered the nefarious Automapper from C# days and thought perhaps there might be such a thing for TypeScript.  There is:  automapper-ts.  The solution to all my problems!  Inside my head I was doing the Snoopy dance.

And then I tried to use it.

It’s not written in a modular way, and despite my following instructions to the letter written by people who had also had issues with importing/requiring/using automapper-ts, I could not get it to work.  The author of the automapper-ts library knows about this issue and has attempted to provide solutions for it, but found that he could not support both a modular approach and whatever you call the previous approach, so has not implemented a solution.

After a day of fighting with what should have been simple, I uninstalled automapper-js and continued to think.  I should have been able to use instanceof() to see if an object was an instance of a class, and use an if/else statement to map it.

public doMap(sourceObject: any): any {
   if (sourceObject instanceof(UserDto)) {
      // convert UserDto to User
   } else {

      if (sourceObject instanceof(User)) {
         // convert User to UserDto
   ... etc

TypeScript did not like this, and my code would not compile for reasons I failed to specifically record.  Something like ‘type is used as a value’ even though there were examples around the web showing this exact usage.

I developed the notion that it might be because my ‘type’ was really an interface.  I have learned that interfaces are best used instead of classes if there are no operations to be implemented– i.e. it’s a data class with properties only, and none of them need to be private.  This is really just a complex datatype, right?  When classes are used, the transpiled JavaScript converts the class to a function, which is unnecessary code bloat.  Conversely, interfaces do not get transpiled, and do not appear in the final code.  However, they do provide what we want at compile time– type checking.  Here is an excellent blog post on classes vs. interfaces.

For these reasons, I try to limit my use of classes to services and components.

As it turned out, the idea that it was the interface vs. class issue causing my if/else tree to fail was not the case.  But I was tired of trying things to make instanceof() or typeof() to work.

My eventual solution?

A Converter Service

Services in Angular are nice because they are injectable, and as such, the service class can be treated like a singleton.

My mapper– which I chose to call a Converter so as not to be confused with map functions on arrays, is a class called Converter with an @Injectable() attribute.  I added it to the list of providers in the AppModule, and can inject it anywhere.

It looks like this:

export class Converter {

   public toUser(userDto: UserDto): User {
      const user: User = {} as User;             =;
      user.thirdPartyId   = userDto.thirdPartyId;
      user.thirdPartyName = userDto.thirdPartyName;
      user.plan           = null; // todo: get from Store

      return user;

   public toUserDto(user: User): UserDto {
      const userDto = {} as UserDto;               =;
      userDto.thirdPartyId     = user.thirdPartyId;
      userDto.thirdPartyName   = user.thirdPartyName;
      userDto.planId           =;

      return userDto;

In time, the Converter service will contain quite a few functions, and will include functions to convert models to view models, such as

toUserViewModel(user: User): UserViewModel.

This approach works well because code that uses the converter can be checked at compile time to be sure the correct types are being used.  Here is an example of an ngrx effect that uses the converter. (In the constructor of the UserEffectsService I have injected the Converter service as converter).  With this effect, if the call to the UserDataService returns an actual user dto (data transfer object) we know the user exists, otherwise we add the user to the data store.

export class UserEffectsService {
    constructor( private userDataService: UserDataService,
                 private converter: Converter,
                 private action$: Actions) {}

getUser$: Observable = this.action$
 .map((action: GetUserAction) => action.payload)
 .mergeMap((user: User) =>

 .switchMap((data: any) => {
 if (data.result && (isUserDto(data.result))) {

 const existingUser: User = this.converter.toUser(data);
 return [new GetUserSuccessAction(existingUser)];

 } else {
 return [new AddNewUserAction(user)];
 .catch(error => of(new GetUserFailureAction(error)))


Problem Solved!





Updating Packages: Payload? Portfinder?

I took a couple of weeks off while guests came and went.  When I got back to my keyboard I checked to see what npm packages were outdated by using the command “npm outdated”.  Since my software is not yet in production, I’m fairly cavalier about updating packages to their latest version.

Thus I saw that Ngrx had been updated to 4.0 from its previous 2.x version.  After dutifully changing the version numbers in my package.json file and re-running npm install, I unsuccessfully tried to compile and run my program.

First I dealt with all the Ngrx issues by following the migration guide  and was really surprised to see that the payload property had been removed from the Action interface.  After fuming for a few seconds, I realized how nice this is.  Consider for a second this bit of code from a reducer:

     const userData = action.payload; ...

Previously, this code would compile under certain circumstances (like above, when the type wasn’t provided for userData).  But what if you hadn’t defined a payload for the action because it was not required?  What if your payload was inadvertently a different type than you actually wanted?

By removing the payload property from the Action interface, you are forced to cast the type of action to the one you really need.  This prevents incorrect assumptions and clarifies the code.  By stating the type of the expected payload and casting your action to the expected action that has that type of payload your intentions become clear and the possibility of misinterpretation or run-time errors is reduced:

    const thisAction = action as LoadUserSuccessAction;
    const userData: UserData = thisAction.payload; ...

The only thing I was really sad about is that, due to performance issues, the Ngrx dev tools integration is temporarily not available. I enjoyed being able to look at the Redux tab in the Chrome dev tools to see what my state was and how it had arrived to confirm that my code was working as expected.  However, they do say they are working to fix the issues and I hope to see it available again soon.

Ngrx issues fixed, I once again attempted to compile and run.  Now I kept getting an error saying that the portfinder module could not be found.  This problem has been reported sporadically over the past year, and advice differed, but I took the scorched earth approach and deleted my node-modules directory entirely and then installed everything clean.  I believe the issue was that not all levels of the node packages were updated.

Recent issues with Auth0 and How I Solved Them

I have watched a number of courses and tutorials online, from great providers such as Udemy, Pluralsight, Front-End Masters, Egghead, Treehouse and others.  I’ll be mentioning some of these from time to time, but today I want to mention what they never talk about in Angular 2+ courses:  user login/authentication/authorization.  At least not in a way that relates to the Real World.

I have struggled with protocols such as OAuth 1.0 and 2.0 and OpenId and others, but after hours of combat laid down my sword and walked away.  It’s not that I couldn’t get them to work, but it was so much work it wasn’t worth it, for me, working alone on a personal project.

And then one day I discovered Auth0, and the angels sang.  You may have discovered it too.  My point today is not to talk about how to implement it– their own tutorials are quite good at that, but to mention something that frustrated me for a while recently.

In the last four months of 2016 I had done a lot of work on my app and implemented Auth0.  It worked fabulously.  Then I had to attend to moving 3000 miles across the country, and couldn’t spend time on it.  Once I got moved and had my computers up and running in June of 2017, I got back to it.  I updated my libraries, and authentication no longer worked.

There were three reasons for this.  One was my fault, and the others were not.

At some point in the last four months, Auth0 changed a couple of things.  You may know that to determine whether a user has been authenticated, you write a little function in the auth service, usually called isAuthenticated(), and this code checks to see if your JWT token is expired or not (this requires the use of the angular2-jwt library):

public isAuthenticated() {
    return tokenNotExpired();

The tokenNotExpired method previously checked for an item in localStorage called idToken.  You put that token into local storage in the callback method for the Auth0 authenticated event, by getting it from the authResult.idToken.

The thing is, they changed the name of the localStorage value that the tokenNotExpired method checks.  Instead of being idToken as it formerly was, it is now just “token“.  However, the name in the authResult remains as idToken.  So now you do this:

this.lock.on('authenticated', (authResult) => {
    localStorage.setItem("token", authResult.idToken); ...

and that part works.  I understand that the reasoning behind changing the name had something to do with “idToken” implying that this identified the user, but since the token is used to authenticate and not identify, Auth0 changed its name, at least for the JWT check.

I am all about making sure that the words you use in your code represent what is contained.  I applaud the decision to change it.  I do not applaud the decision not to let everyone know it changed! And I wonder why they did not go a bit further and change the property of authResult from idToken to token.

The second thing Auth0 changed was they deprecated the use of the lock.getUserProfile method and changed it to lock.getUserInfo.  This wasn’t a breaking change, but good to know about.

And the one that was my fault?  I ignored my MacBook for days, maybe weeks, when it alerted me that I needed to update.  Meanwhile, libraries for the new version of Chrome were installed in my node modules.  For some reason, this caused my localStorage not to actually set items.  So even though my code was correctly setting items in localStorage, they were never persisting.  Once I updated the computer, everything magically worked.

And we all lived happily ever after.



An Atypical Angular Coder

Let’s just get it out there.  I spent 26 years in the software world, working for companies in the Seattle area starting with Microsoft and ending with Expedia.

I didn’t start learning to program until I was 31, so you do the math– I’m pretty old for a programmer these days.

I don’t have a college degree.  I learned to program by teaching myself in an era where there were no courses online and I only knew one programmer, who worked for the law firm at which I was a secretary.  He encouraged me, but didn’t want to teach me, so I floundered around, reading books and experimenting and eventually figured some stuff out.  In those days, companies were desperate for programmers and the bar for getting a job was pretty low.  But getting my foot in the door was what I needed, and the rest is history.

Now I have retired early and moved to the Blue Ridge mountains, and enjoy learning on my own, coding stuff for myself and possibly one day for online consumption by others.

I’m a woman, in case you haven’t guessed.  I want to encourage everyone to learn, but especially other women.  Things are different now than they used to be.  I had to learn to be aggressive to succeed, many do not.  I was called “sweetheart” at meetings, “stupid” by co-workers who didn’t understand what I was suggesting (autocomplete, anyone?) and generally got by the old-fashioned way– bowing and scraping to the guys.  Don’t get me wrong– I like guys, especially smart guys (I married one!).  But it was hard to do at times.

In the last 5 years, I managed to work with some fabulous people, many of them men, who weren’t so condescending and whom I developed great friendships with.  One in particular got me really interested in JavaScript.  (We were on a team that used a variety of technologies in the stack:  Java for the service, C# for the business layer, C# MVC and JavaScript for the client.  It was a huge code base and we had strict measures in place for code quality and pull requests.  All of the developers were expected to be able to code in all stacks.  Toward the end of my tenure there, we also started using AWS API Gateway and Lambdas, and a little bit of Angular.)

Because my friend Mark had piqued my interest in Angular and reactive programming, I was way ahead of everyone on my team and was able to help when they chose Angular to use on a new product.  But by doing so I realized how much I didn’t know, how much I still have to learn.

So here I am, writing about this in the hope that you will find some ideas and solutions as you learn the same things I do.  I’m not a teacher and I won’t be able to explain how things work all the time, but I will explain what I figure out to address certain situations, even if it just means pointing to some other source.  You might tell me a better way to code some things, and I would be grateful.  Hopefully we help each other learn and improve in this quickly-changing world of open source software.

Since I didn’t go to computer science classes, I won’t always be able to use the terms others would use, and this is a shame.  I learned patterns by doing them, not by reading about them and then being able to say oh! I think I’ll use the adapter pattern for this… so I can’t even really tell you which pattern I’m using at times.  But maybe it doesn’t matter, as long as the code is done well.  So let me emphasize:

I am not an expert!

My goal is not only to get better at Angular, but also at some point to feel comfortable giving back to the open source community.  There are far too few females doing that, and I don’t think I’m too old yet!