RXJS 7 was recently released to much fan fare, but buried deep inside the release was the deprecation of the “toPromise()” method on the Observable type.

For example, this sort of code :

let myPromise = myObservable.toPromise();

Now gives you the following warning :

@deprecated — Replaced with firstValueFrom and lastValueFrom . Will be removed in v8

That last point is the most important thing here. Not only is it deprecated in RxJS 7, but come version 8, it will be completely gone. That’s big, because often libraries deprecate methods but keep them around for backwards compatibility, but not this time!

Luckily, there is a simple work around that doesn’t require much of a change at all to how you were already using toPromise().

Using FirstValueFrom and LastValueFrom

FirstValueFrom and LastValueFrom are new utility methods inside RxJS 7 that more or less give you the same functionality as toPromise(), just in a different format. To use them, simply import from rxjs and give them a whirl!

import { firstValueFrom } from 'rxjs';
let myPromise = firstValueFrom(myObservable);

firstValueFrom does exactly what it says on the tin, it waits for the very first result from the observable, returns it as a promise, and unsubscribes from the subject.

lastValueFrom however, waits until “complete” is called on the subject, and then returns the last value it received. It’s important to note that if your subject never calls complete, then your promise will never be resolved.

Why?

The obvious question would be, why? Why remove toPromise() in favor of adding static “helper” methods. There’s actually a simple reason.

When using toPromise(), if the Observable completed without ever emitting any value at all, the Promise would resolve with a value of undefined. However, when you were using this in code, it was impossible to tell if the promise itself returned undefined, or it returned nothing. This has been the case ever since RxJS was released.

To be able to differentiate between no value, first value, or last value from the Observable, it was decided a static method, off the Observable prototype was a better solution than changing the behaviour of the toPromise() method all together.

One of my pet peeves when utilizing a CSS boilerplate framework like Bootstrap, is that it can completely take over elements in ways that I may want to back out of later. Bootstrap isn’t the worst offender of this these days, because for the most part you have to apply specific styles to an element, but it still happens more often than I care to count.

Lately I’ve been utilizing the “revert” css property and it’s saved me a bunch of time trying to work out what a default value should be. It’s a somewhat lesser known feature, but certainly one that I think people could be using more often.

Utilizing CSS Revert

Let’s take a simple example, whereby I override the CSS of all buttons within my application. Something like so :

button {
  background-color:blue;
  color:white;
  border-radius:5px;
  border-color:blue;
}

What happens if I want to style a button with a class of “plain-button” to look like a default button. Basically, I want the button to “remove” all CSS styles. In the past I might try and simply overlay CSS on top to override things yet again. Something like so :

button.plain-button {
  background-color:transparent;
  color:black;
  border-radius:0px;
  border-color:gray;
}

This code probably looks correct on the surface but it’s actually wrong for a couple of reasons :

  • I’ve had to guess the default CSS values (of which they are wrong by the way!)
  • Default CSS values actually may look different per browser or OS (Namely on Mac devices, default buttons look completely different!)
  • Sometimes setting CSS values has unintended side effects, namely adding borders sometimes removes the border shadow in some browsers etc.

All of this boils down to us not *really* reverting the CSS as much as we are trying to work out the values to make it go back to looking like a plain button.

Instead, we can do something like so :

button.plain-button {
  background-color:revert;
  color:revert;
  border-radius:revert;
  border-color:revert;
}

Revert allows you to reset a CSS value back to the browser specific style for that property, for that element. This means you no longer have to “guess” the style but can simply say “Whatever the browser default is, use that”.

Revert All Property

Resetting each property can be cumbersome. And it doesn’t stop another developer adding additional properties to our root element yet again. But there is a handy shorthand for saying “Reset everything”. It looks like so  :

button.plain-button {
    all:revert;
}

The “all” property does what it says on the tin. It takes every possibly CSS property and reverts them all to our browser specific stylesheet. You can even then start styling something from scratch below :

button.plain-button {
    all:revert;
    color:gray; //OK revert all, except make the text gray. 
}

Revert vs Initial

You may be confused about the usage of “Revert” given there is another value you probably have seen called “Initial”. They work in similar ways, but there is a large difference to the output .

Initial works by resetting CSS values to what the W3C spec says for that particular element. This typically means styling elements in ways you did not expect. When it comes to buttons, this is especially true because the W3C spec does not define a style for buttons, and therefore if you used “initial”, it means removing all browser and OS specific styling on that button (Which you may want by the way!). Another tricky one is that the W3C spec defines that the default display value for a div is “inline”, not “block”, again rather confusing as every browser defaults a div to be displayed as a block element!

Revert instead resets the CSS values to what your browser thinks is the default. Which often means styling things in a way that you’ve probably come to expect, and as such, this is definitely the one I use more often.

 

If you’ve ever run a website through a pagespeed analyzer like Google’s Site Speed or GTMetrix, you’ve probably seen a recommendation that you should lazy load images below the fold. That is, when your website first loads, only show images that are actually visible on screen, then as you scroll, load additional images as you go.

The interesting thing about this is that much of the guides out there will focus on javascript snippets that utilize something like swapping a data-src attribute to the src attribute of an image based on where the page is currently scrolled to. While this works, it can often lead to weird loading phases where you see the image flash while you scroll over it. Not ideal!

But browsers now support lazy loading out of the box. Meaning that there’s no javascript snippets required! Just a small attribute on an image and the browser will take care of when the image should be loaded! Often this leads to a much smoother experience (And one that the browser has obviously optimized for).

Lazy Loading Attribute

To lazy load an image, simply add the loading=”lazy” attribute like so :

<img src="example.png" loading="lazy"/>

Notice how the src attribute is still set like normal? That’s important because it provides backwards compatibility for any browser that doesn’t support Lazy Loading. If we check caniuse.com however : https://caniuse.com/?search=lazy%20loading there is actually great support and it’s really only old browsers such as IE, and Safari that haven’t quite implemented it yet.

Seems easy right? But what if you just want to add lazy loading to every image on your site, and not have to go back and manually add it everywhere?

Add Lazy Loading Globally

If we want to set all images to be lazy loaded by default, then it’s actually rather easy using Angular Directives. Something like so :

import { Directive, ElementRef } from '@angular/core';

@Directive({
    selector: 'img:not([loading])'
})
export class LazyLoadImagesDirective {
  constructor(el : ElementRef) { 
    el.nativeElement.setAttribute('loading','lazy')
  }
}

This simply takes all images, and adds the loading=lazy attribute. Again, if the browser doesn’t support lazy loading it really isn’t a big deal, the directive still runs and any legacy users won’t see a difference.

I’ll also note a key important detail here, and that is our selector for our directive very specifically is :

@Directive({
    selector: 'img:not([loading])'
})

What this actually says is run this directive on all img tags that *do not* already have a loading attribute set. This is not because it might run twice on the same element, but because it allows us to override the directive and still eager load images in the rare cases we don’t want them lazy loaded.

For example, the directive will not run on the following element :

<img src="example.png" loading="eager"/>

I recently had a need in an application to have an “In Memory Queue”. Simply put, a list of items that I add to, and I can request the oldest items out of the queue. It’s a very common construct in other programming languages/platforms such as Java or C#.

Unfortunately, Javascript does not have native queueing functionality, and so I had to build my own. What I found however, is that Javascript itself actually has all the pieces of the puzzle to make this a real breeze.

First I created a simple Queue class. Because I am using Typescript in Angular, I could use generics to say which type of items my queue would hold. The first thing I add to my class is an array of items of T (My type), that I then initialize to being empty.

export class Queue<T> {
  items : T[] = [];
}

My enqueue method is easy. I use the native javascript function of “push” on an array to add items to the end. Notice also that I specify the item being added is of type T.

enqueue(item : T) : void {
  this.items.push(item);
}

Then for my dequeue, I can use the javascript function of “shift” which essentially pulls items from the *front* of the array. This is important because it means we are adding to the back, but pulling from the front, much like how a queue works. Also important to note is that when we call shift, if the array is empty, it will return undefined.

dequeue() : T {
  return this.items.shift();
}

Next I wanted to add a couple more helpers such as peeking at messages (Reading the next message off the queue without actually removing it), and knowing if the queue is empty. So the class in it’s entirety looked like so :

export class Queue<T> {
  items : T[] = [];

  enqueue(item : T) : void {
    this.items.push(item);
  }

  dequeue() : T {
    return this.items.shift();
  }

  peek() : T {
    if(this.items.length) {
      return this.items[0];
    } else {
      return undefined;
    }
  }

  isEmpty() {
    return !this.items.length;
  }
}

Then we just use our class :

let myQueue = new Queue<number>();
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);

let nextItem = myQueue.dequeue(); //Dequeues the number 1

Is this the most performant code in the world? Absolutely not. But using existing javascript language features, we created a queue in no time at all!

I recently came across a project that had a certain function littered throughout the codebase. It was in many HTML templates and looked something like :

{{$any(myVariable).property}}

At first, the use of the dollar sign $ threw me off (Is someone introducing jQuery here?!). But infact, it’s a special operator used in very rare cases within Angular templates. It can actually take a while to come across a scenario that requires it’s use, but when you do, it’s a life saver.

The first thing to note is that everything about this resolves around Angular AOT compilation. You can read more about it here : https://angular.io/guide/aot-compiler

But in short, most angular projects will be set to have AOT turned on, but only for production. This generally means that if you run “ng build”, you will not use AOT, but if you run “ng build –production”, you will. To be absolutely sure, open your angular.json and hit Ctrl + F for instances of “aot”, and check which configuration they are set under. If in doubt, and you just want to test things out, you can also run “ng build –aot” to force AOT on anyway.

With that out of the way, what does AOT actually do? Well it compiles your application ahead of time. And as part of that, it can (or by default, will) do a strict type checking process. That is, it will ensure that all types used within your application are used correctly (Numbers are treated as numbers, strings are treated as strings etc).

On this project, I noticed that if I built the application using AOT, I got an error similar to :

ERROR in src/app/app.component.html(1,3): Property 'firstName' does not exist on type '{}'.

And again, I did not get this error without AOT turned on.

To recreate the issue, I was using a component that looked something like :

export class AppComponent implements OnInit {

  myPerson = {}; 

  constructor() {
  }

  ngOnInit(): void {
    (this.myPerson as any).firstName = 'Wade';
  }
}

Notice how the myPerson variable is initialized as an empty object (Something that someone writing in vanilla javascript may do). In Angular, I can cast this object to an “any” type to set properties in my component. But what about in the HTML?

I had something like :

{{myPerson.firstName}}

Which seemed fine to me! But AOT uses strict typing and wants to ensure that the myPerson object actually will have a firstName property. Unfortunately in this case it can’t.

And that’s where the $any() function comes in.

{{$any(myPerson).firstName}}

This now converts the myPerson object to an “any” type, and allows it to act as such even in HTML. It’s basically identical to the cast we do in the backend of our component.

The main thing you’ll be asking yourself is, but when will I do something like :

myPerson = {}; 

In my case, I didn’t! But I was using a library that was initially build for vanilla javascript and exposed objects as such. And for that, the $any() function was a life saver!

I’ve recently gotten into the habit of using the finalize operator when using RxJS in Angular. For the most part, if you’ve used languages that have try/catch statements, they generally have a “finally” statement too. For example, in plain old javascript you can do something like :

try {
    DoWork();
} catch {
   //An exception was thrown here
}
finally {
   //Regardless if an exception was thrown or not, always run this block of code next. 
   CleanUp();
}

The finalize operator in RxJS really isn’t that different.

Let’s imagine that we have a piece of code that calls an API endpoint. When calling this API endpoint, I want to ensure that I lock the UI so that while we are saving any data, the user doesn’t click anything. To lock the UI, I have a simple boolean variable. The code might look something like so :

lockUi : boolean;

DoWork() {
    this.lockUi = true;

    this.CallAPI()
    .subscribe(result => {
        //Do something with the result.

        //Unlock the UI because we are done. 
        this.lockUi = false; 
    });
}

CallAPI() {
    //Call an API here and return an observable (But for now, mock it)
    return of();
}

Works well but what if our CallAPI method errors? What happens then? Our UI would be locked forever, which we may not want. So instead what you might do is try and change the DoWork method to capture the error and handle that use case too. We can do this within our subscribe callback like so :

DoWork() {
    this.lockUi = true;

    this.CallAPI()
    .subscribe(result => {
        //Do something with the result.

        //Unlock the UI because we are done. 
        this.lockUi = false; 
    }, 
    error => {
        this.lockUi = false;
    });
}

This may seem OK since we are only duplicate one call to unlock the UI, but what if we keep adding additional things that we want to say “No matter what, always do this on error or on success”. Seems a little silly to copy and paste everytime. And that’s why finalize is so handy!

We can take the above and change it to :

DoWork() {
    this.lockUi = true;

    this.CallAPI()
    .pipe(
        //Finalize to always unlock UI no matter what. 
        finalize(() => this.lockUi = false) 
    )
    .subscribe(result => {
        //Do something with the result. 
    });
}

And that’s all there is to it! A nice handy way to ensure that code gets run no matter the observable outcome!

I was recently banging my head against the wall for a very annoying error that only occurred on my build server, but not locally. The error in question was when a component referenced an external style sheet, I was getting the following error :

Couldn’t Resolve Resource ./foo.css Relative To foo.component.ts

I’m going to go through a tonne of solutions here, any one of them could be your solution so don’t dismiss any of them until you’ve given it a go. The basis for this error is that whatever build tool you are using (Gulp or Webpack), can’t find your style file. In some rare cases, this also applies to your component not being able to find your template html, and all of the following solutions still apply.

You Are Using Inline Styles

If you are building templates using inline styles, then often it can be a bit of a copy paste error when you end up with something like so :

@Component({
    selector : 'app-header',
    templateUrl : './header.component.html',
    styleUrls : ['h1 { float:left }']
})

And this may look very obvious but it’s happened to me before! If you are looking to use inline styles, you should change that styleUrls to be styles like so :

@Component({
    selector : 'app-header',
    templateUrl : './header.component.html',
    styles : ['h1 { float:left }']
})

You Are Not Using Any Styling At All

The next solution is actually similar to the previous. Imagine that you don’t want to be using any styling at all, so you simply delete the style file and blank out the URL like so :

@Component({
    selector : 'app-header',
    templateUrl : './header.component.html',
    styleUrls : ['']
})

This will still in some cases (Depending on your build pipeline) blow up. If you are intending to not use any styles at all, just completely remove the styleUrls all together like so :

@Component({
    selector : 'app-header',
    templateUrl : './header.component.html'
})

Relative vs Absolute Paths

I mostly see this in projects that move from things like Gulp to Webpack or vice versa. Even more so again when people are copy and pasting code from other projects. In some cases, Gulp for example likes absolute paths like so from the very root of your project.

@Component({
    selector : 'app-header',
    templateUrl : './core/layout/header.component.html',
    styleUrls : ['./core/layout/header.component.css']
})

Whereas WebPack prefers relative paths from where the component.ts file is located. So if the css file is in the same folder we can change everything to be relative :

@Component({
    selector : 'app-header',
    templateUrl : './header.component.html',
    styleUrls : ['./header.component.css']
})

However, again, this is totally dependant on what build tool you are using. The majority of projects will be using Webpack and therefore require relative paths, but just incase, and if you aren’t sure, try the absolute URL style yourself just to rule it out.

Case Sensitivity

This one has caught me out plenty of times as a Windows developer who typically has build agents running Linux. Windows is case-insensitive for file paths. Therefore this will build completely fine on a Windows machine :

@Component({
    selector : 'app-header',
    templateUrl : './header.component.html',
    styleUrls : ['./hEaDeR.component.css']
})

However it will blow up when building on a Linux machine. The solution is obviously pretty simple, either rename the styleUrls to the correct casing *or* rename the file in Source Control (Which in of itself can be difficult on Windows). Either way, don’t discredit a small casing issue completely blowing things up.

The concept of Attributes vs Properties in Angular can get confusing at times. Mostly because often there attributes and properties with the exact same name. If we take a simply example, using an input html tag such as :

<input type="text" id="nameInput" value="Jim">

Here we have an input HTML tag that sets a value of “Jim”. This sets the initial value of this input to “Jim”. If a user edits this value and changes it to “Jane”, we can observe two things :

  • If we use getAttribute(‘value’) on this input, it will return our initial value of “Jim” not “Jane”.
  • If we fetched the DOM property value for this input, it would be our new value of “Jane” not Jim.

This simplifies things for us a little because we can then boil down attributes vs properties in Angular to the broad concept of :

  • Attribute – Represents the initial value and does not change.
  • Property – Represents the current value and can change.

In Angular, we can go further to describe attributes as belonging to HTML. However once a page is rendered (broadly speaking), an attribute does not change and is purely used in the initial rendering process. Whereas a property is almost a “binding” to the current value, including the initial value set by an attribute.

Things can get a little complex in our heads when trying to understand whether we should use a property or attribute. But for the most part, we will be using properties. That’s because many HTML Attributes have a 1 to 1 mapping with DOM properties. Therefore getting/setting a property on an HTML element will generally speaking be fine.

There are however exceptions to this rule. Notable elements that have attributes, that do not have properties. A good example of this is the colspan attribute of a table cell like so :

<td [colspan]="4"></td>

We are passing in a hardcoded value of 4 here, but we may also pass through something like a property of our component :

<td [colspan]="columnCount"></td>

Either way, we would receive the following error :

Can't bind to 'colspan' since it isn't a known property of 'td'.

This is because colspan only exists as an attribute (And it’s important to note that in the error message, specifically it is talking about a known property). You would even get this message if you were just using string interpolation like so :

<td colspan="{{columnCount}}"></td>

However Angular gives us a way to set an attribute value, and avoid using properties. That is like so :

<td [attr.colspan]="columnCount"></td>

This sets only the attribute, and not the property. What this does tell us though is that colspan is not “designed” to be changed after the initial render (Of course, in modern times there are always exceptions to this rule).

Other common examples of attributes that don’t have corresponding properties would be all aria-* tags.

What about the other way around? Do properties exist that don’t have corresponding attributes? Of course! Plenty. Really any custom property you add to a component is a property that exists in the DOM but does not exist in HTML attributes!

Hopefully this goes some way to explaining why we have attributes and properties, and what their subtle differences in Angular are.

As part of a recent build of mine, I added the website to Google Webmaster Tools. Now, among other things, these tools provide insight into how Google sees your website functioning, and also gives feedback on any issues it found while crawling your pages.

A big focus for Google in the past 10 years, has been how websites function on mobile. Do they load in a reasonable time? Does the javascript require a huge amount of resources that makes your phone too hot to handle? And more recently, does your website function in a way that’s easy to use on a mobile touch screen?

That last point is frankly, a little subjective, but it’s one that Google is taking a keen eye on. And when you fail their test, you get a rather vague message of “Clickable elements too close together”. I actually searched the web for any tool that could actually pinpoint what exactly on my website was causing the issue, but to no avail. So unfortunately, there is a bit of trial and error involved. But you can speed up that trial and error by knowing where to look.

Element Size And Margin – The Key Culprits

Almost universally, you’re going to run into this problem when a clickable element is either too small, or it’s too close to another element that is also clickable. An example I will show you shortly was that I had a button that opened the side menu right up against a link that takes you back to the homepage. The button itself was too small, but additionally, the fact that there was no gap between the two items was also a mobile usability problem.

I hunted around for the exact numbers that I should be aiming for, and there seemed to be a little bit of a consensus on the following :

  • Any element that is clickable (That is not a text link) should be at least 48x48px (e.g. Buttons, images, SVGs etc)
  • Any element that is clickable should have at least 8px margin on all sides from any other clickable element

These are your starting points, so if you can look at your website right now and immediately identify problems with the above, then you are good to go! Start making changes and testing those updates using the steps below.

Finding Clickable Elements

One way to help you diagnose any mobile element problem is to add an outline to any element that is clickable. For that, you can use the following CSS :

a, input, button, svg {
    outline: 1px solid red;
}

Note that I’ve put SVG in there for my own needs (Since I have clickable SVG’s on my site), but should you not, then you can remove it. By the same token, if you have clickable elements that you want to check if they overlap, then be sure to add them.

You can either add this CSS in development *or* you can use something like Chrome Dev Tools to see things on the fly.

In my particular case, I ended up with a view like this :

Clearly now I can see that these elements are too close together and are actually overlapping somewhat. Using this visual tool, we can easily identify elements that don’t have the appropriate margin, and easily rectify them.

Every Element Is Tested

Something that caught me out is that elements I thought would be “invisible” to Google were in fact causing problems. This included a slide out menu that is only shown on mobile, and an iframe to another site. I figured that in the iframe’s case, I would not be penalised since I didn’t even think Google would bother loading the iframe in any testing tool. I was wrong, very very wrong!

This may be obvious, but just in case it isn’t, don’t assume something is not relevant to what Google is testing. If it’s on the page, or it’s reachable in some way, it could be causing the error.

Testing Changes

The easiest way to test if your changes have fixed the problem is to go to Google’s official tool at : https://search.google.com/test/mobile-friendly. I’ll be the first to admit that this tool can be a bit finicky and it sometimes takes a few changes to finally get your website the green light. Elements that I thought would be causing issues, actually were fine, and it was other inconspicious items that were doing all the damage. The trick is, just keep adding margins and testing your changes until you get it right.

If you are having to make large scale UI changes that you aren’t happy with, you still want to get to the point where Google is liking your page, and then you can start rolling back changes one by one, to see which changes actually had an affect. Again, it’s painful because Google will not tell you exactly which elements are causing problems, so trial and error is really your only way.

Some code I was working on required me to delve into what the differences between Empty, Never and Of were in RxJS. Specifically, I had a method that returned an observable purely so that I could “wait” or “subscribe” for it to finish (e.g. It did not return an actual result). Imagine something like this :

myMethod() : Observable<object> {
  //Go and do something
  return this.http.post('/myurl', null);
}

In reality, I’m not interested in the result, but I am interested in waiting until the call is complete. Therefore, I may have code such as :

this.myMethod().subscribe(x => {
  //Continue something here. 
})

Where I ran into issues, was what if I wanted to short circuit myMethod()? What if I had a cache or sorts, or logic that determined I didn’t need to call the API at all? What should I return to still fire my continuation method? The results were interesting..

Using EMPTY

RxJS 6+ has a special type called “EMPTY” that acts as an empty observable. When I first used this, my code compiled fine but while testing, I noticed that my continuation never fired.

The documentation for EMPTY (And it’s deprecated sibling empty()) state :

Creates an Observable that emits no items to the Observer and immediately emits a complete notification.

It’s important here to note that while the observer is completed, it emits nothing on it’s way to doing so. For example :

EMPTY.subscribe(x => {
  console.log('Empty Emit'); //This never fires. 
}, 
null, 
() => {
  console.log('Empty Complete'); //This does. 
});

What this means is that if you are using EMPTY to short circuit your code, but your code subscribes to the returned observable, EMPTY will in fact not work.

Using NEVER

While, given the name, I didn’t have high hopes that using NEVER would solve my problem, I did want to see how it functions. So using this code :

NEVER.subscribe(x => {
  console.log('Never Emit'); //This never fires. 
}, 
null, 
() => {
  console.log('Never Complete'); //This never fires. 
});

NEVER well… It never fires anything. It doesn’t emit anything nor does it complete the observable. This may be useful in very limited cases where you need to return a value, but you don’t want subscribers to act on it *or* for anyone to act on the observable completion.

Using Of

That brought me to using Of. I had used this before but slowly drifted to using EMPTY when in fact, using our example :

of({}).subscribe(x => {
  console.log('Of Emit'); //This fires. 
}, 
null, 
() => {
  console.log('Of Complete'); //This fires. 
});

This works perfect! Not only does the emit fire, but the observable also completes. I would like to point out that in this example, I have used of({}), if you instead use Of() with no value, then you will instead complete the observable but not emit a value (Similar to EMPTY). Of simply wraps a static value in an observable and emits immediately, allowing you to short-circuit otherwise asynchronous methods.

Which One To Use?

If you want to return a value and call all subscribers, then you must use Of(value).  If you want to return a value and *not* call subscribers, then use EMPTY. If you subscribers not only act on emit, but also on completion and you want to avoid this behaviour, use NEVER.