@ngrx Angular RxJS Testing

Upgrading to Angular 5: Using HttpClient, JSONP with parameters

Angular released version 5 – deprecating the old http module “@angular/http” with the replacement of “@angular/common/http“. Along with the http module, the jsonp module was also deprecated in favor of a better replacement which is included with the new HttpClient. The usage of jsonp is a little bit different with this version. My open source project, ngx-typeahead – is an auto suggest directive for Angular-  allowing to query a remote source either with jsonp or http (and with version 0.1.0 – static list as well). In this article, i’m sharing the steps I took for upgrading the package to use HttpClient and performing a jsonp request with parameters.

Step 1: Updating The Module Imports

First, lets import the relevant modules. Within src/modules/ngx-typeahead.module.ts, I replaced the code so it will import the new modules. Similar to before, there are 2 modules for using http and jsonp:

I also update the src/modules/ngx-typeahead.component.ts to import HttpClient only. Notice that the alternatives to “RequestOptionsArgs” and “URLSearchParams” have been updated too and are used inside a utility function (respectively, “HttpParams” and “HttpParamsOptions”:

Step 2: Updating The Http Service Injection

In contrary to the previous version, with Angular 5, “jsonp” is used as a method of the http service. All I had to do is change the injection of the http service to use “HttpClient” as well as remove the “Jsonp” injection:

Step 3: Updating the Jsonp call with parameters

In the old version, i used the jsonp service and had to create an options object which includes the parameters to attach for the request. Eventually, I passed 2 arguments to the jsonp method that was used (“get” by default):

With the new HttpClient it’s a little bit different. “jsonp” is a method that performs the jsonp request. It takes the first argument as the url and the callback string name as the second argument.

Where jsonp request’s parameters should be placed with Angular 5?

I had a small challenge with this one: the params in this case should be concatenated as string parameters to the url argument. Since i’m using the new “HttpParams” to construct a params object, I can use the “toString()” to get all parameters as url search parameters and add it to the url:

You can see and experiment with ngx-typeahead in this plunkr demo and in production on my open source alternative player to YouTube: Echoes Player