SharedModule best practices in Angular7

In this post we’ll examine how to make our Angular modules future-proof. We’ll see what exactly should go into a SharedModule and how the rest of our application integrates with it.

A SharedModule is just a concept of structuring your application – there’s no built-in class in Angular for its functionality.

It saves you from constantly reorganizing your modules and components.

Here’s the deal: when you start a new Angular project your second step (after generating the template) is to add a new empty module. By convention we’ll call it SharedModule. You do exactly two things in it:

  1. Import and re-export dependencies for other modules (CommonModule, FormsModule, Angular Material or Primeng modules, etc.).
  2. Declare all dumb, reusable components, pipes and directives here and export them.

And here’s what you don’t do in your SharedModule:

  1. Declare services. They don’t really belong here. If they are application-wide singletons then they’re going in your CoreModule (which we’ll explore in a future post). If they are feature-specific then they’ll go to the feature module where you require them.
  2. Add business logic. Everything in your SharedModule is meant to be used by one or more of your feature modules. That means they must be dumb and generic as hell, so you don’t limit yourself when you need to use them.

If you’ve an existing project adhering to these conventions would be much harder. However it’s worth restructuring, because eventually you’d get circular dependencies.

Let’s see a super-straightforward SharedModule example:

As you can see we do the two things outlined above. First we import commonly used Angular modules required by other modules. Again, SharedModule is dumb as hell, it won’t really use most of these modules.

Then we declare our pipe (for the sake of brevity I only added one) and export it, so that other modules can work with it.

That’s all our SharedModule is and does.

Other modules and the SharedModule

All other modules in your application (RootModule, all your feature modules) can potentially import and depend on the SharedModule. The SharedModule typically won’t depend on your application modules, rather on 3rd party libs.


A SharedModule saves us from two types of Angular pains:

  • Maintaining a module dependency list in each and every module we have. When you add a new module dependency you just add it to your SharedModule and be done with it.
  • Having to worry and figure out circular dependencies between our own modules. By moving every pipe, dumb component and directive to one place we greatly eliminate potential circular dependencies.

Source code

I’m maintaining and developing a repo on GitHub. It contains Angular7 best practices. Follow this link to the relevant part of the code.

RXJS subscription management in Angular

If you’re reading this then you’re probably familiar with the fact that Angular uses RxJS and embraces the reactive paradigm. You might be familiar that RxJS is based on the Observable class. Let’s recap what this means.
To extract any information from an Observable we need to subscribe to it. A subscription is a bunch of optional callback functions. We can define a success, an error function and a completed function, all of them optional. When an Observable emits, RxJS invokes the proper callback function.
Subscriptions aren’t free though, you’re required to tell RxJS when you’re done with them. It’s pretty easy, you need to invoke their unsubscribe function. The problem is – when and how to do that?

Not unsubscribing

 The easiest – and worst – solution is to ignore the problem. Subscribe to an Observable and leave it at that. When Angular destroys your component the open subscription will simply leak it.
Your subscriptions are holding a reference to the hosting component. If you don’t unsubscribe then you’ll create a memory leak with your whole component.

Manual subscription management

Let’s take a step in the right direction. Usually you’ll set up your observables in the ngOnInit lifecycle hook. There’s a corresponding hook when your component is destroyed, called ngOnDestroy. By simply storing all your subscriptions as members of your component class you can just call unsubscribe on all of them in the destroy hook.
This is a solution to the problem, but not a great one. For simple components it might work. But when you are adding more subscriptions later, you might forget to unsubscribe from them. And let’s face it, we just copying and pasting the code lines in cases like this, and will forget to change the variable name eventually.

Semi-automatic management with takeUntil

 We can harness the power of hot observables, aka Subjects. The logic is the same as when you’re using manual management. The difference is that you create a subject. In every observable subscription you pipe your subject through the takeUntil operator.
You also create an ngOnDestroy hook and complete your subject there. This will unsubscribe from your observables.
There’s a slight catch though. Order matters when piping operators, and you generally want to put takeUntil to the very end. The actual reasons are beyond the scope of this post, refer to this article on Angular in Depth.

Using the async pipe

 My personal favourite is to delegate the subscription management to Angular. This results in much less code and very straightforward components. Angular has the built-in async pipe for consuming observables. You’d use them in your component template.
Notice how all the subscription boilerplate code is gone. That’s a great thing, we need to maintain less code!
Also, when your component is destroyed Angular automatically unsubscribes from your observables. Though there are some caveats you should look out for.
If you use an async pipe multiple times on the same observable you’d get a different subscription. This could lead to multiple API calls. Fixing this will be the subject – pun intended – of my next post.

Source code

I’m maintaining and developing a repo on GitHub. It contains Angular7 best practices. Follow this link to the relevant part of the code.


A Stack Change

In the not so distant past I was assigned to a very interesting HTML5 / JavaScript project. I used to say that I’m familiar with JS and I even add it to my resume with a modest years of experience number. Needles to say that as soon as I had to dive deeper into the JS world my confidence vanished away.

On the other hand I learned tons of new stuff. I can only compare the current knowledge gaining to the very beginning of my career, when I started to learn C# and ASP.NET.

The reason I write this post is twofold. First, I want to propagate the idea of abandoning your well-known technology stack for a while to learn something entirely different. I believe there’s succinct and fundamental diversities between the C# and the JS world. It successfully moved me out from being stuck in a warm and fuzzy world with little uncertainty. It also opened lots of new opportunities.

The other reason is that I plan to write some follow up posts on the more intricate stuff that was quite a pain to figure out in the current cutting edge JS stack. To name a few, I got the chance to work with AngularJS, RequireJS, Node, NPM, Bower, Grunt, Karma, Jasmine, etc. I also had the opportunity to get into a more intimate relationship with functional programming practices and JS per se.

Brace yourselves, complete stack change is coming.

How I failed to pivot because of the ‘coolness factor’

iBeacons? Build something with them!

A couple of months ago I was browsing the news and stumbled upon Apple’s iBeacon technology. After some digging on the internet I figured I would like to build something awesome on it. I started brainstorming with my best friend and all-time business partner on the potential and what we could do. Initially I had a hard time trying to persuade him thinking out of the box. Apple has set some boundaries for this technology in the way they pivot it. They proposed indoor navigation or showing some price tags. However in two or three quick iterations we had the idea ready: use it as a foundation of a new dating app. Ironically we failed because I was unable to think out of the box – and didn’t see the need to the pivot.

The idea – let’s revolutionise dating!

The app’s workflow was pretty simple: you fill a form about yourself and your dating preferences. The app immediately starts to publish this information on Bluetooth Low Energy. In the same time it starts a subscriber and polls for other people’s broadcast. If someone is within range and there’s a match you and the potential partner would receive a push notification, asking whether or not you like the other party. You’d be able to show interest in the other party by hitting a nice green “Interested” button. Alternatively you could politely turn them down by tapping on the red “Not interested” one. If both parties are interested they are notified and they can begin getting to know each other. Due to the very nature of BLE and iBeacons, these people would be in close proximity, so this would be pretty easy.

Why would anyone use this thing?

Now what is the purpose of this? Why would I fiddle with my smartphone instead of just walking up the other person? In one word, what is the pitch? Well, for starters the sad thing is that everybody is always hooked on their phone. I’m not in the position to judge this, but sometimes it’s pretty hard to deal with it. People are perceiving the world through their smartphone screens, and in the end, more aspects of “real” life would march to that screen. The other point is that everybody has insecurities. It takes courage to walk up to another person and initiate a conversation, particularly if you have romantic intentions. We’d just facilitate the meeting process by providing a painless (or at least, less painful) way to deal with rejection.

The technical problems

I implied in the beginning that we eventually failed to build this app. What was the problem? In short I was too focused to build something on iBeacons and BLE that I built the whole idea around it. And Apple has some technical limitations in place which made it impossible to deliver the product using this technology. In a few words, your app would have to run in the foreground, and the other party’s app too. This of course is not a viable scenario for this kind of app.

And failing to overcome them

I was so blinded by the cool new technology factor that when it turned out we cannot do this I didn’t start to pivot, despite all the startup literature I read. And we were pretty close, with just a little pivoting, we could have delivered a working product. The proof is ntice, a Hungarian startup with the exact same idea.


So what’s the conclusion? It’s pretty clear from the outside and common sense dictates that you need to pivot or persevere (or, worst case, let it go). This scenario was clearly a pivot one, the solution would be to ditch iBeacon and work on some check-in based stuff like Foursquare. Or ditch Apple and go with Android. Or something else that never occurred to me. But never ever let the opportunity of using a cool technology cloud your judgement.

Wordnik API for Windows 8 and Windows Phone 8

I was thinking about creating some app dealing with words for WP8. One big hurdle was getting definitions for user-entered words, so I started searching for online services with APIs for the purpose.

The first obvious choice was Google Dictionary, but the API is not public (and unsupported), despite all the requests from the dev community. I saw a link there for Wordnik, a word and phrase dictionary with a nice API. The only problem was that they didn’t have a C# API which could be used with Windows 8 or Windows Phone 8. The nearest thing to C# was their Java API client, so I grabbed that and rewrote the stuff for using the portable HttpClient. This means that you can use the API client with Windows 8 and Windows Phone 8 as well. The result is this project on GitHub, a portable library for the Wordnik API.

The API client can exercise the whole Wordnik API, all you need is to get an API key from Wordnik (a fairly easy process), and put it in the Api/ApiKey.cs file.

I hope it would prove useful for someone else as well.

Git Viewer, my first WP8 app is published

In my previous post I wrote about a Windows Phone 8 app I built. Now it’s available in the app store.

As a recap, this app lets you connect to your GitHub repositories and check various aspects of them. If you’re interested, you can also check out the source code on GitHub. I’m not done with the development, currently there’re some new features ready, but I haven’t done testing and updating the app. I welcome any participation to provide some nice GitHub experience on Windows Phone 8 as well.

I made an app for Windows Phone 8

It’s winter and I’m on a holiday so I have lots of free time at my hands. I thought that maybe I could spend it in a productive fashion, so I wrote an app for Windows Phone 8.

The app itself is a GitHub client, which lets you check out your repositories, view files and diffs and do other stuff. It’s open source, of course, and hosted on GitHub. Check out the source code!

Connecting to the API

I knew it won’t be a walk in the park, but there’s a very nice project on GitHub which lets you use the whole API, called OctoKit.NET.  It even has a portable library for Windows Store. But not for Windows Phone, so you have to take portable as in portable to another Windows 8 PC. Something is seriously messed up here, and we’re heading towards a new kind of DLL hell.

But it’s not the fault of the guys behind OctoKit, this is the current ecosystem. I thought that I’d fork their project and do some changes to make it a portable library for Windows Phone 8. Nope, that’s not going to happen. Networking code is not part of the portable stuff, you have to do that in your Windows Phone project.

So I did that there. Wrote a client for the API parts I actually needed, and used that. It wasn’t a huge work, and JSON.NET made it very easy as well.


There’s decent MVVM support in the WP8 controls, but I ran into some horrible stuff which seriously messes up properly architectured code. One being the ApplicationBar control, which doesn’t support bindings. Even the sample project has that horrible commented out stub like BuildLocalizedAppBar. Also it doesn’t support commands, so you’ve to have event handlers in your XAML code behind, instead using the ViewModel for this stuff. That’s a shame. I hope that Microsoft fleshes this out in some upcoming release.

Some limitations

I wanted to build a page for viewing your source code files and diffs. I’m a fan of short files with one class in them, but there’s a perfectly fine chance that files grow bigger. The idea was to grab a TextBlock and bind it to the file text. Later when I feel like syntax highlighting, I’d ditch the TextBlock and try something else.

However I noticed that a TextBlock (or any other control, by the way) tends to cut off its content after some height. It turned out that the maximal control height in WP8 is about 2040 pixels. So I wrote an abomination to split the stuff into small chunks and add it dynamically to a StackPanel. Ugly and broke MVVM brutally. I know about a control written for WP7 that doesn’t cut off stuff, but there were some changes between the versions, and it wasn’t worth the effort to adapt it for a fun project like this.

Lack of unit testing support

Now this almost made me gave up the project. I wondered what can be the Windows Phone 8 Unit Tests template in Visual Studio, but I never thought that they want me to run my tests on my actual phone (or buy Windows 8 Pro and use an emulator). Am I supposed to connect a phone to a build server and run the tests there if I’m serious about WP8 development?

The excuse was laughable at best: WP8 code relies so much on WP8 libraries that the unit tests will surely touch libraries depending on the platform. I did a fairly big amount of SharePoint unit testing, which enforces that too, but never needed to run my tests in a SharePoint server. The whole point of unit tests would be to test a unit of code, and if you really need it, provide some mocks or stubs for the dependencies. I think that Microsoft got this one really bad.

So what’s the point?

Windows Phone 8 as a development platform doesn’t seem that mature for me. There are lots of quirks and you have to do lots of workarounds for simple stuff. A template project requiring workarounds is something I haven’t seen yet anywhere else.

The development tools on the other hand are fairly robust, it’s a pleasure to write mobile apps with Visual Studio at last. However Microsoft doesn’t seem to be in a position to ship incomplete libraries for developers, as this clearly won’t help overcome their chicken and egg problem of nobody develops on the platform because there are not enough users because nobody develops apps.

I think I’d consider iOS as my primary mobile development platform, and write some fun side projects if I have the time and resources for WP8.