Wednesday, October 30, 2019

Angular MediaService Example

Some of you may have encountered older links or books that describe how to use the media query service via the ObservableMedia service.  This has been changed since 2018, although you will find posts even from Google Developer expert, Brian Love, on his post showing the older way.

What's changed is found on Github showing the reason why ObservableMedia is now obsolete.
















There's not a whole lot to change, but if you are new to Angular like me, this may be a minor curveball when trying to follow along with books or posts that are a little outdated.



First, the import statements will change:

Older way:
import { ObservableMedia } from '@angular/flex-layout'

New way:
import { MediaObserver } from '@angular/flex-layout'

Since you usually inject this service into a constructor of your component, you simply change the type as shown next.

Older way:
constructor(private media: ObservableMedia){}

New way:
constructor(private media: MediaObserver){}

In the second bullet above describing the changes, you will see you cannot directly subscribe to the MediaObserver service.  However, you can access the service via a layer in-between your application code and the service via the $media property.

Here is an example from a good Manning Book called "Angular Development with Typescript SECOND EDITION" by YAKOV FAIN and ANTON MOISEEV, but with the updated code using MediaObserver instead of ObservableMedia service.  

constructor(private mediaObserver: MediaObserver){
    this.watcher = 
      mediaObserver.media$.subscribe(
        (change: MediaChange=> 
        {
          this.activeMediaQuery 
            = change 
              ? `'${ change.mqAlias }' = (${ change.mediaQuery })` 
              : '';
          console.log(this.activeMediaQuery);
        })
  }