On Converting from Angular 1 to Angular 2

Dear diary (blog) – I’ve neglected you. Its been over 2.5 years. I see you haven’t changed – still patiently waiting (along with my unused dental floss, stack of possible junk mail, to-read articles, holiday cards to respond to…) Habits are hard to maintain. Well, I’m back today and I might be seeing you again more frequently.

Note to reader (and mostly myself, since this entry is to keep from having to solve the same problems over again in 3 months): screenshots and example code will be added.

My software development stack changed significantly this summer. Angular and asp.net have each been in their own 2+ year limbos, while waiting for their successors. Each was released in final form this summer: Angular 2 and asp.net core. Along the way, visual studio code has established itself as a very fine code editor (in the Webstorm genre), especially for client side coding.

I have been working on a responsive version of my website, fpnotebook.com. More than a year ago, I created a first version based on angular 1 framework.

In the last month, I worked on converting the first version to one connected to a backend, to manage identity/authentication/authorization and instill backend functionality such as user notes stored in a database. I started with an asp.net core mvc app for note management, which I will discuss in another post. My intent was to get this working with the database and then add an Api that the angular app can call. Identity is the tricky part, especially communicating with client via tokens, and once Identity Server 4 is finalized, I will implement this part.

Conversion from angular 1 to angular 2 is not trivial (at least for me), and I spent the better part of a week converting version 1 to version 2 and completed a working draft: angular 2 version of FPN. It is not complete. The workshop allows selection of content, but you cannot yet generate quizes or other output. Annotations do not work.

My thoughts:

Angular Cli
At first, angular 2 seems so much more complicated than angular 1. With angular 1, I included a couple of scripts on my index page and it all worked. I knew where all my files were; started with js and ended with js.

Angular 2 is not like that. You recognize Angular 2 “quickstart” as a misnomer, after you set-up the app and tooling, set up the vs code editor for launch/debug, typescript compilation, add testing…

However, angular-cli, despite the warnings about still being in beta, worked very well (A+). Magically (via node, webpack) it sets up an environment that takes care of all of the drudgery. It really is a quickstart that includes a basic setup with browser serving, testing (karma, jasmine), typescript compiling, minification, optimization.

Need to add a component with angular cli? At the command prompt, “ng g component named-thing” adds a NamedThingComponent in its own directory, along with a spec test file, html template and css file (or less or scss). The same is available for services, directives, pipes… Angular CLI sets up most of the wiring (add to module file, include in component annotation).

Most of this works great, but there are caveats. Testing is tricky – as mocking dependencies (modules, components, services) is not straight forward. However, the main app component serves as an example for setting this up, and there are quite a few examples on the angular website.

For sometime, I was viewing the test output via the console window, frustrated that I could not see it in the typical nice jasmine output I prefer. At the same time, I was wondering what the Karma debug button did. Add the jasmine report viewer npm package and voila, the jasmine test view is back.

When I setup my workspace, I open the root working directory in windows explorer. I then open the folder in vs code and in two separate powershell windows. In one powershell window, I type ng serve (sets up the app running at localhost:4200) and ng-test (sets up a browser running karma/jasmine). I use the integrated terminal window in VS Code (Ctrl-`), which I have set to use powershell, to navigate directories and run commands such as those to generate components, directives, services…

The angular-cli set-up is a magical black box, and customization is not intuitive. Scripts and css are added to the angular config file, not to the index.html. Although I can get visual studio code to debug launch the site, I cannot get debugging to work in VS Code with typescript. I had to debug the javascript in Chrome which was workable.

CSS Frameworks

As with nearly all of my single page apps, this responsive version uses bootstrap 3.  Bootstrap 4 has been in alpha for sometime.  Even if I wanted to try the angular material framework, it is still in alpha.  So far, of what I’ve seen with material, I like the bootstrap look better than material.  Having styled responsive websites from scratch with CSS, it is a relief to have professional looking content produced in early development stages without extra effort (albeit with similar appearance to every other bootstrap page).  I often use Bootswatch to at least change the Bootstrap color themes.  I use the LESS precompiler and import the bootstrap/bootswatch “variables.less” file into my own LESS style sheet.

The other decision with Bootstrap, is whether to use the official bootstrap javascript file for dynamic effects (e.g. carousel, accordion/collapse), or to use ng-bootstrap/ui-bootstrap.  I used angular-ui bootstrap for the last version, but the angular 2 ui-bootstrap (ng-bootstrap) is still in development for angular 2.  I’ve found that most of the standard functionality of the official bootstrap.js integrates well with angular (except for more complicated solutions).   In any event, for this solution, I stayed with the standard bootstrap.js.

Finally, there is the integration of css and angular 2.  Angular cli makes this very easy.  When components are created, a css (or less or SCSS) file is also created that is linked to the component and also namespaced for the particular component (using a CSS ID).  In other words the css/less/scss for slideshow would be specific for that component.  At first  I had assumed that I could put  CSS in a parent component and that would flow through to the child components, but that did not work.   For css affecting the entire application, I used the main css file.  However, I had to keep the main css as a plain css file, as I could not get the LESS or SCSS compilers to process the main styles file.  There is probably a way to do this via angular cli setup (without resorting to use other tooling e.g. gulp).

Angular Code, Typescript, Observables and assorted language features

I seem to like languages written by Anders Hejlsberg. I started with Turbo Pascal in the 1980s, C# since the mid-2000s, and I really like Typescript. I like the structure (modules, classes, properties, public/private, interfaces), typing, conveniences (generics, string templates). Yet, there are times when I need to actually use a dynamic object and can just fall back to dynamics and plain old javascript. Finally, using Typescript is using ES6 and ES7 NOW, compiled to compatible code for today’s browsers.

Pairing typescript with angular 2 works very well. Using typescript with angular 1 was awkward. Typescript has modules and classes, and I found using this with angular modules and controllers to be, at times, a confusing mess. Now with angular 2 written in typescript, the code is much cleaner. Plenty of angular 1 code was no longer needed when I moved to angular 2.

Asynchronous processes are tricky. Promises were a bit confusing, but I did somewhat grasp them in the last couple of years. I at least could copy/paste examples from my own code and that of others, modify them and they worked. Observables are another story. When I follow online observable examples, I can grasp that exact example, and it works. But I am challenged when customizing the examples for my own use. Ben Lesh has some very nice intro videos online (check out those from angular connect), and he recommends getting to know a few high yield operators (map, filter, scan, mergeMap, switchMap, CombineLatest, Concat, Do). I am learning, and hopefully the next new approach to async will not come so soon that I can’t master this iteration.

Some mappings from angular 1 to 2 are simple and straightforward. Controller to Component, for example, is not a giant leap (albeit with new annotations, import statements, module definitions). Routing is much improved and I am using the angular version instead of the angular ui version (which I used for my angular 1 projects). It sounds as if the angular team focused on routing efficiency, lazy loading… and I think this shows in the final release. I like the way angular uses native html functionality (e.g. [src] maps to its native src attribute, (click) maps to its native click functionaliy)

One of my initial roadblocks in moving from angular 1 to 2 was how to implement the routing. Using angular 1 with angular UI router, I had routes that used a template with slots for 2 or 3 named outlets- each route defined what would fill each outlet. To solve this, I ended up routing to component views, which would be a basic template comprised of slots filled with other components (instead of router-outlets). For example, the page-view-component has a spot for the chapter-component and page-component.

There are areas which were more difficult to remap. Hrefs are replaced with routerLink. And routes are no longer prefixed with ‘#’ In angular 2, an href will reload the browser/entire framework and navigate to the target (browser refresh and all, lost data…); contrast with routerLink which uses the current angular routing. Although, not difficult conceptually, this remapping was time consuming. One frequent snag was that [routerLink] = “code”, not “string”.

ngBindHtml became [InnerHtml] which at first glance, appears the same, but has one significant difference: only basic html works, not angular directives. We want to avoid href links due to their reloading the browser, but if we convert these to routerLink they will not work within [innerHtml]. My fpnotebook page content for this version, sits in precompiled json code with hyperlinks. This worked very well with ngBindHtml in angular 1, and without it… the project would be hampered. Fortunately, dynamic component template solved this problem.

Angular 2 has changed significantly during its alpha and beta cycles (which is what alpha/beta are for). However, code example online searches yield many answers that will no longer work. Although this is less an issue than asp and asp.net (which has decades of deprecated examples on the web), it does make adapting solutions for the final angular 2 release more difficult.

Several VS Code plug-ins are helpful: Path intellisense (for filename typing in import statements) and Angular 2 typescript snippets.

Overall, the angular 2 experience is a very positive one, especially by using angular cli. The draft in progress is here: angular 2 version of FPN.

The next steps are to integrate with a asp.net core backend and identity server 4. I hope to add code examples and screenshots to this post in the near future.

Until next time (which hopefully, dear diary/blog, will be sooner than 2.5 years).

Posted in Coding | Leave a comment

December Fpnotebook Updates

Its been a while since the last post. November and December were busy months at the FPN homestead.

I’ve started logging all Family Practice Notebook updates. 25 major topic updates in December. Not only is the list of updates more complete now, but I’ve stepped up the number of resources reviewed monthly.

December also saw a new, re-vamped look to the Fpnotebook website with some added functionality. Let me know what you think.

Many more topic updates are ready for January release. And in April 2014, I expect to release an Iphone and Android version.

Have a great new year.

Posted in Medicine

September 2013 Fpnotebook Updates

I started work with atmoapps (programmers of the Tarascon mobile app) on native mobile app versions of fpnotebook.  These are planned for release in the first quarter of 2014.  To allow for a more automated demonstration of highlights from site updates, I am creating a new topic in fpnotebook “fpnotebook updates” which will appear in late October.  


It was a busy month of reading (about 40 hours on 20 review articles), but here are the highlights.  Intensively updated the airway chapter:  http://www.fpnotebook.com/Lung/Airway/index.htm based on attending Dr. Levitan’s Practical Airway course in Baltimore, MD.  Great course.  


Was surprised at how little I remembered about Pituitary Adenomas.  Updated at http://www.fpnotebook.com/Neuro/HemeOnc/PtryAdnm.htm


Also updated the hernia section at http://www.fpnotebook.com/Surgery/GI/AbdmnlHrn.htm based on Critical Decisions in Emergency Medicine.


September Em:Rap was as usual chock full of new information, but pediatric cardiology was particularly an intense listen/read:

Crashing Newborn: http://www.fpnotebook.com/NICU/Birth/NntlDstrsCs.htm

Congenital heart disease: http://www.fpnotebook.com/CV/Peds/CngntlHrtDs.htm


Prescriber’s Letter had various medication precautions (Ketoconazole, Mefloquine, Plavix after CVA) and possible risks (more hype than data) regarding amlodipine and fish oil.


Posted in Uncategorized

A Challenging Day in the Emergency Department

They wait outside their ED room’s doorway, with their arms crossed.  A simple visit over, all but the discharge medication faxed, patient instructions added, discharge button clicked.  The visit started well with a pleasant conversation during the examination.  Evaluation efficient and appropriate.  But now they are waiting to go home, and their eyes are throwing daggers.   I could tell them I was interrupted on my way to the desk to complete their discharge. I could tell them I was interrupted by an elderly man who could not breath in Room 2, or chest pain in Room 3 or the clinic calling with a transfer and the radiologist calling with a new malignancy on CT.   But I simply apologize and repeat this cycle over and over again today.  Some days are like this.

One of the aspects of the emergency department that I find most challenging is patient flow in the midst of interruptions.  Critical patient arrivals, patient surges from triage, phone calls, asynchronous result review, documenting, RN questions and pharmacy clarifications.  In busy ED’s, this can amount to more than 10 interruptions per hour in some studies.  My interruptions do not come close to this, but I still at times feel overwhelmed.  

There were times when working clinic, I could fall an hour behind with work-ins and complex patients.  But my patients knew me and they would still be cordial to me despite the delay.   This is not always true in the ED.   I try to move fast, practice the best quality I know how, provide the best service I can and disposition as quickly as possible.  Despite this, they stand in their room’s doorway with their arms crossed angry that they are still waiting for discharge.  

In clinic, there was an overflow escape known as a schedule that would limit the flow of patients in.  On the worst days, there was still time for a sandwich and bathroom break.  There was still the appreciation for care from most of my patients.  

But today the emergency department surge continues.  It is on these days, that histories and exams are clipped and compressed and sign-outs to hospitalists are mediocre at best.   No time to open a reference or  consider a quality differential.  Hungry, fatigued and operating on clinical reflexes and base knowledge.  Small conflicts with sparks of dissatisfaction by patients and hospitalists.  I could explain the attempts at maximizing patient status over hours in the ED.  How I tried to stave off an admission, but this failed.  Now the family is frustrated with the long ED course, and the hospitalist sees this as a dump.   

So I continue to optimize my emergency department task juggling and patient flow.  But today as I leave the department, my shift over, I can still see a patient standing in their room’s doorway with their arms crossed and angry.   This was a challenging day.

Aside | Posted on by

Medical Informatics and Godel, Escher, Bach

In college I read (about half of) Godel, Escher, Bach by Douglas Hofstadter.  I understood less than 50% of what I read, and remember little now.  But I remember the challenge of trying to understand the “interweaving” of mathematics, art and music into common, recursive patterns.  It is a  transient glimpse into creative and brilliant minds, seeing information in awe-inspiring, unique ways.

  Medical informatics, especially my work on fpnotebook.com. blends clinical science with programming/coding and design/illustration.  My trifecta – as enticing for me as Godel, Escher, Bach.

Outside of my primary job (Emergency Department and Epic optimization for our organization), I split my work on fpnotebook in half: medical note taking in the first half of the month and programming/designing in the second half.  

  As with the masters I admire in medicine, I have my mentors in coding and design.  My over-flowing book shelf has been augmented in the last few years with EM:Rap (Emergency Medicine) audio and Pluralsight (coding) and Lynda.com (design) videos.  I’m a voyeur of brilliant and creative minds.  Lessons in emergency airway management and bedside ultrasound, mixed with c# or javascript, with a side of photoshop, illustrator or 3DS Max.  Eclectic but uniquely satisfying.

Unlike Godel, Escher, Bach, medical informatics offers a challenge that is practical – an end result with utility.  With no shortage of project ideas, every month I have a 2 week opportunity for a creativity deep dive – blending what I’ve learned as an online apprentice.  Two weeks is an ideal project time frame for a solo developer – a sprint of creativity and immersion, without the fatigue, frustration and unwieldy nature of my prior year-long mammoth projects.  These small projects tend to build on others in a modular way and mistakes are made on a much smaller scale.

This month I created a stand alone search application for the fpnotebook.com website.  Those clinicians who tolerated my ramblings to this point, may wish to stop reading here.  The rest is in the form of notes to self, and to developers up too late solving that last infuriating problem, that should work, and wondering why Google has led them here instead of well traveled stackoverflow.

 The application is a single page application, served from  asp.net mvc.   This allows for easy coding, compilation (js, less), web api, authentication, and deployment.  I like Typescript as well, but did not use it for this project.  Note to self – don’t forget to add to the web config:

    <modules runAllManagedModulesForAllRequests="true"/>

This is a data heavy application.  6000 pages, 4000 concepts, 20,000 titles with synonyms, and multiple maps linking topics to one another (in and out), as well as to concepts, keywords and the hierarchical tree the topics hang from.  

Complex data queries are my main focus for this project: how to filter topics in multiple ways. Ultimately (in a future 2 week project) I want to preview topic contents and their inter-relationships as well as to link custom user content. For this project, I needed to have easy access to processed site data for dynamic searches. I first made calls to the MVC controller, and then a web api, and then with odata queries.  All very seamless.  However, I kept thinking about how many times users would hit my server and database with over-lapping, inefficient queries.  That’s when I tried json files.

 I wrote a c# windows utility that queries the fpnotebook database and writes out the json to files using newtonsoft.  10 json files – most the size of small images or thumbnails (8 to 300 kb), 2 files at 1 mb each, and one file at 3 mb – in total less than 7 mb.   High bandwidth on the first download, but cached for a month until the data changes. Asynchronously loaded in a handful of seconds over a decent internet connection.

When loading json files with javascript, the parent directories will change on deployment; use server code to store the current parent URL path.

The application uses a themed version of bootstrap with angular-ui instead of the standard bootstrap plugins.  Angularjs and Typescript (along with jquery and underscorejs) are my favorite javascript tools.  Angular is tricky to write inside of Typescript.   But I like using angularjs for the view model and asynchronous data access and Typescript for the utility and business logic code.   Testing with jasmine works well in Visual Studio (with the Chutzpah plug-in).

So another 2 week development sprint is over and I’m ready to return to medical articles.  Next week I’ll attend the Levitan Airway course in Baltimore, kicking off another month of gently weaving together medicine with art and code.

Posted in Coding, Uncategorized

By the Way of the Door

“By the way”, as we are leaving the exam room, “I just wish my headache was not so much worse with coughing.” Brain stem mass.
“No doc, not in this part of the neck. I mean the swelling is here.” Lung cancer with supraclavicular node.
“Do you ever get a song in your head, you just cannot stop hearing.” Temporal lobe epilepsy.

The “by the way”, typically as we’re leaving the exam room, is a universal primary care daily experience. Weeding through the myriad of “by the ways” to pick out the uncommon or rare, hair-raising, sentinel finding seems an impossible task. But, over multiple encounters in successive years, primary care built clinical relationships help to hone the alarm system to fire when random clues arise that are discrepant with a patient’s established history. As long as I listen.

There lies the rub in the Emergency Department. No prior relationship, or worse a pigeon-holed prior relationship. Limited time to listen. Frequent redirection. Interruptions. Early boxing of histories into the chronic headache or low back pain container, or the multiple other reflexive responses to similar histories. Insufficient provider processing of histories recorded by scribes. Fatigue, especially towards shift end, especially over-night.

I have more reminders of bad acting illness in the emergency department. Looking for head bleed, abdominal mass, ectopic pregnancy, myocardial infarction has a high daily yield in the ED. So you memorize common pitfalls, decision trees. There is less gestalt and more guidelines, more decision-rule calculators. More advanced imaging and testing. But the history drives everything, and no abdominal CT will catch the CNS mass causing intractable vomiting.

Dr Mark Jaben “ranted” about this in EM:Rap – Talk to your patients.. His “rant” can be summarized in one word: Listen.

Posted in Medicine, Uncategorized

FPNotebook Update Highlights – August 2013

A few highlights from my August reading:
Tourniquets and Topical hemostatic agents from August 2013 Critical Decisions in Emergency Medicine (both links have the reference).

I do not see much in the way of massive uncontrolled bleeding, but better to read this now and store it away for some future date when I will be glad I read it. Topical hemostatic agents are not mainstream outside of the military, but would be great to have this around (wonder what the cost is? shelf life?)

Hypocalcemia, Hypercalcemia and Hyperparathyroidism from Parathyroid disorders in AFP.

How often I skip over the abnormal serum calcium, noting “need to come back to that” as I’m reviewing the metabolic panel. Nice algorithms in this paper for systematic approaches.

Finally, I never really thought about the acidity of IV fluids, but Scott Weingart of the EMCrit blog describes this on EM:Rap this month.
Here is my summary of what he said: Crystalloid acidity

Posted in Medicine, Uncategorized