Solving Common Angular 2 HTTP Pitfalls: No map() Method for respose.json() & No Http Provider

I had so much fun helping mentoring a couple dozen developers yesterday in SSW’s Angular Hack Day here in Sydney. It was an awesome day from organizers to students.

This post is about the Number 1 problem all students seemed to have, and how to solve it.

The Most Common Problem: map Not A Function

When you make an HTTP request to a JSON endpoint, you map the response text to a JSON object, like this:

When the students ran their own code, which more or less looked like the segment here, they got an exception like this:

2016-04-24_13-31-23

The reason for this is that the result of the HTTP call is an Observable. An Observable has nothing defined by default except subscribe. You need to import any other operator manually like

If you rely on autocomplete in your editor, and it shows a couple of versions for every operator, remember to choose the with with “/add/” in it. As this is the file that add the operator to the Observable definition.

You cannot add * unfortunately.
Update: You can import all RxJS operators in one call like this:

Single Include

You can also move the import(s) from every TypeScript file to the main entry point of your app, likely the file with the bootstrap() call.

Depending on how you set up your compilation and module loader, the entry file import might not work. It works with the SystemJS use you see it in the official Angular 2 quick start though.

Obviously, if you think the entry file include is a hacky way, just add the imports on top of the each file that uses them.

Another Problem: No Providers for Http

Some students also were getting a different error:

2016-04-24_13-52-18

The forgotten part this time was adding the Http providers to the bootstrap. Something like this:

One last tip: Make sure you included the Http file in your scripts if you are starting from a quickstart start or so. As the Http module is included in a separate file in Angular 2.

A Quick Shoutout to Dan Wahlin

During the hack day, students asked me for a good example that shows the solution above. It was not in the official examples (the 5 minutes quickstart, and the Tour of Heroes).

The best I have found on Github is Dan Wahlin‘s Angular 2 JumpStart sample.

It’s named similarly to his Udemy course for Angular 1. I remember his AngularJS in 60-ish minutes YouTube video was a key block in building my Angular 1 learning when I first started it back in 2013.

Thanks for everything, Dan :)

Different People, Different Challenges

With various people hacking away, I got to see different problems that people had getting up and running with Angular 2.

For some people, just setting up Node was more challenging than it should be.

Some others had issues with the sample APIs they chose, because they didn’t have cross domain support (CORS), or returned XML by default and they needed to add an Accept header explicitly.

Some were wondering how to use RxJS to combine results form 2 separate HTTP requests (getting city weather from one, and information about it, or an image URL from another).

How About You?

All these variations got me pretty curious. What was the biggest blocker you had when trying to play with code in Angular 2?

What were your own challenges?

Tweet them to me on Twitter (just mention @Meligy), or just write it down in a comment below.

Fix TypeScript Autocomplete for RxJS Operators And Helpers In NodeJS

I have been working on a Node application, and wanted to use Reactive Extensions (RxJS). All previous interactions with it were in web apps that run in the browser after some SystemJS / Webpack massaging.

At first it looked OK. I could build an Observer, and subscribe to it. I tried to use some operators, and this is when I got stumbled.

The Problem

I had a sample Observable, and I wanted to call flatMapTo on it, but I couldn’t!

Autocomplete only showed the subscribe method, as below:

2016-04-19_07-05-23

Just importing the specific operator file (which modifies the Observable interface and adds the operator method to it) didn’t seem to get the operator autocomplete (or successful compilation at times) to work.

I didn’t want to have to add each operator manually anyway, and this is Node not browser, I don’t have to be picky about imports (and again, it didn’t work anyway).

Note:

I was specifically trying map(), which I was able to get to work with ES2015 targeting (I’m working with Node 5, which has fair ES2015 support).

But that’s because an Observable is also an Iterable object that you can loop over, like an array.

I was not able to get switchMap() (Rx v5), or even it’s v4 equivalent flatMapLatest() though, or any other operator than map() – before I noticed I was not even calling that as an operator.

The documentation suggested the following line.

But it only threw an error. Which was very weird, because I could find the typings registry entry with this very name.

There were other suggestions for other platforms, which didn’t work for me anyway!

I also struggled to find examples of using RxJS operators with even something like Angular 2. Hence I’m writing this blog post.

How To Get TypeScript Intellisense To Work With RxJS

The main key to working with this was using the “KitchenSink” Definition file. This was also confirmed by looking at:

Property ‘distinct’ does not exist on type Observable<CustomType>

I can use this no problem because I’m in Node and not much worried about the size of the code, etc.

However, this post was not enough to get it to work. I still had a lot to fiddle with. As I mention later, I tried many things, and everything I found working stopped working afterwards.

Until I could nail it down to the following steps:

Install From NPM

You can get that by

Make sure you got at least version beta.6, not beta.2.

Add Definition File

You can do this from your tsconfig.json, like:

Or in each TypeScript file if you choose to, at the top of the file:

Gotchas

For the most part, the previous steps are going to be enough. However, I have found a few more gotchas in different editors, most of them are around WebStorm, which is crazy, as outside Rx, it seems to be an awesome TypeScript IDE.

I like WebStorm because it has the best autocomplete in strings (like paths and imports), and in tsconfig.json (which is outdated in VS Code).

Also, the gotchas sometimes happen in VS Code anyway. I have been going crazy between the two, as soon as I get something to work, undo it and repeat the exact steps, it doesn’t work.

Operator And Type inference

Sometimes type inference doesn’t work. I have found VS Code to be better at this than WebStorm.

In this example, autocomplete for sample1$. will give autocomplete for any, which is OK as it’ll accidentally give autocomplete for RXJS operators.

But if you want proper autocomplete:

Note the : Observable<string> bit.

Observable Helper Methods

These are methods like like of, range, etc. I have found their autcomplete to the worst, it’s very flaky at best.

A few things seemed to help, like importing from "rxjs/onservable".

(Vs from "import {Observable} rxjs")

I have also found that doing import {Observable} works better than import * as Rx.

When everything fails, going to TypeScript compiler in WebStorm and building current file, or even restarting WebStorm (Yes!!) helps fix autcomplete issues, especially if you changed your references and imports a few times. It just gets confused and doesn’t work well until an IDE restart.

Disclaimer

Just in case it’s not obvious for those not familiar with TypeScript. I have been doing JavaScript for so long. I’m not the person who can’t code without a fully-functional autocomplete.

But since autocomplete is an essential advantage of going the TypeScript way, and I have been loving working with RxJS from the demos I saw, I wanted to take it as a challenge more than anything else to see what it would take to get this working.

A Quick 10-Min Video To Start Writing Angular 2 With No TypeScript Setup

Hello everyone,

In this video, I share a very simple tip that I earlier shared with a few Newsletter subscribers and ng-sydney members, about the easiest way you can get to play with Angular2, without worrying about shims, SystemJS, TypeScript, or RxJS.

I also give you another hint for when you want to create a “proper” project, not just a playground.

Too Long; Didn’t Read (Watch)

  • To start a new Angular2 playground, go to angular.io, scroll down to the hellow world example, and click the “TRY IN PLUNKER” button
  • If you need a proper project, just google “Minko Angular2 Seed”, click on the Angular 2 Seed Github repository, and clone that (maybe with flag --depth 1 for clean history)

Let me know if you have any questions.

A Web Developer’s Macbook Pro 15 Wishlist

I’m due for a laptop update at the end of the year. I love to follow news about the laptop brands I care about though. Apple is on top of the list.

I only have one Macbook, as I use Windows very often. I got my Apple Macbook when I wanted a *nix friendly native OS for development, and I felt that Linux just doesn’t cut it.

Of course I realize that *nix tools are coming to Windows relatively soon, I’m not sure whether my next laptop will be a Macbook.

But there are things I definitely like about Mac OSX, and the laptop itself. Battery life is one, and the power available in the form factor and current weight is very cool as well.

So, if I’m going to buy a Macbook for my next laptop, this is what I wish Apple would include in a 2016-2017 Macbook Pro 15:

  • A touchscreen!
    C’mon Apple. You are seriously behind on this one

  • Non Retina screen
    The 1440×900 screen is lovely already.
    At least offer the option for those willing to take it for the battery benefit

  • Long lasting battery
    12+ hours, at least

  • An extra right-side “Control” keyboard key
    Eat a bit from the spacebar key. It’s OK.
    As a right-handed developer, with a lot of tools defaulting to using “Control” not “Cmd”, that key will be a saver

  • Same CPU class as before
    Don’t go to these “U” CPUs, keep the quad core CPU, just update to latest generation

And what could be a really nice bonus, although I’m not holding my breath:

  • 32 GB RAM :) :)
    Because, why not?!

  • Same size and weight, with better ventilation
    I don’t want a thinner or lighter Macbook. It’s perfect as it is now.
    I want one that doesn’t feel hot too often that it has a series of fan-controlling apps though!

It’s a VERY long shot to expect that Apple will read this, let alone listen, but who knows…

How To Include AbcPDF XULRunner Folder As Linked Item In Visual Studio?

I was working on some PDF generation for a customer that used AbcPDF in their ASP.NET MVC website.

The work was to move from basic MVC views written especially for PDF rendering, to reusing the same MVC views we send to the HTML browsers.

With more sophisticated markup, came more CSS styling. The default IE engine seemed to lack a few CSS features we used a lot (example, the :not() CSS selector). So, we decided to use the Gecko engine.

The rendering was much better, with a single exception, that the option to choose media type (screen, print) could not be switched. It had to always be print. I guess a few other browser settings were not applicable as well.

Installation

All I needed to do, to add Gecko, was to install the ABCpdf.ABCGecko NuGet package. Something like:

It took quite a while, and at the end, it showed me a message, saying that I need to manually (hate that word) copy a folder called XULRunner21_0 to the MVC project’s bin folder.

The Firefox / Gecko XULRunner Folder

The folder is needed for AbcPDF to connect to Firefox 21 (what’s used in v9, I guess it’s 38 in v10).

The folder, which has so many files and subfolders, was present in the root of my ASP.NET MVC project.

I didn’t want to have to commit this ~40 MB folder to our source control. The customer used NuGet package restore and didn’t want to keep binary files in source.

I know different people and different projects handle dependencies differently, and it can get interesting, but in my case, it was not wanted.

So, I modified the web project .csproj file, and added the following after a PostBuild <Task> in the file:

This made the folder show up in the project web project root in Visual Studio, and get copied to the bin folder, but the actual files were pulled from the package folder, not left in the website root itself.

The approach in general is very useful for adding an entire folder as a linked item in Visual Studio. I hope that little trick has helped!