First let's find out why TypeScript is a good option for building NativeScript apps.
1. Why TypeScript?
TypeScript is a first-class citizen in NativeScript. It is used by the core NativeScript team to build the NativeScript framework itself. Here are a couple of reasons why you would want to use TypeScript for developing NativeScript apps:
- TypeScript compiles to JavaScript. When the compiler runs, it catches any errors that you might have in your code so that you can act on them immediately without waiting for the NativeScript compiler to finish. This means more productivity for you as the developer.
- TypeScript allows you to use ES6 Features such as classes, modules, arrow functions, template literals, and much more. This means more tools at your disposal to organize and write better code.
2. Tooling
To fully take advantage of the features that TypeScript offers, I recommend that you use the Visual Studio Code text editor. It has an IntelliSense feature which provides smart auto-completion while you're writing TypeScript code, it integrates with Git, and it has debugging capabilities as well.
Best of all, there's also a NativeScript plugin which will make you more productive when developing NativeScript apps. One feature that I find useful is the emulator integration. This allows you to run the emulator directly from the text editor and debug the app from the text editor itself. Visual Studio Code is free and available on all major platforms (Windows, Linux, OS X).
However, if you don't want to leave the comfort of your text editor, you can also install extensions that will make coding with TypeScript better. For Atom, there's the atom-typescript plugin. For Sublime Text, there's the TypeScript Sublime plugin.
3. Overview of the App
The app that we're going to create is a weather app. It will have the following pages:
- A main page which shows the current weather along with some relevant information such as the temperature, air pressure, and humidity.
- A forecast page which shows a five-day forecast of what the weather is going to be for the next five days.
![]() |
![]() |
4. OpenWeatherMap
The weather data will come from the OpenWeatherMap API, and just like any other API, you need to sign up for an API key in order to use it. Go ahead and sign up for an account, I'll wait. Once you're logged in, go to the API keys page, copy the value of the key field, and keep it somewhere safe. You'll need it later, once you start creating the app.
![]() |
Now that you know what the app will look like, it's time to actually start creating it. Start by creating a new NativeScript project which uses the TypeScript template:
- tns create weatherApp --template typescript
- - common
- + constants.ts
- + navigation.ts
- + requestor.ts
- + utilities.ts
- - fonts
- - pages
- + forecast
- * forecast.css
- * forecast.ts
- * forecast.xml
- * forecast-view-model.ts
- + main
- * main.css
- * main.ts
- * main.xml
- * main-view-model.ts
- - stores
- + location.ts
- - app.css
- - app.ts
Install the Dependencies
The app requires a couple of dependencies: the NativeScript Geolocation Module and Moment. You can install the Geolocation module with the following command:
- tns plugin add nativescript-geolocation
- npm install moment
Common Modules
Before we take a look at the code for each of the pages of the app, let's first take a look at the custom modules which will be used throughout the app.
Constants
The constants module (common/constants.ts) contains all the constant values used throughout the app: things like the base URL of the OpenWeatherMap API, the API key that you got earlier, the paths to the endpoints that we will be using, the character codes of the weather icons, and the wind directions.
- export const WEATHER_URL = 'http://api.openweathermap.org/data/2.5/';
- export const WEATHER_APIKEY = 'YOUR OPENWEATHERMAP API KEY';
- export const CURRENT_WEATHER_PATH = 'weather/';
- export const WEATHER_FORECAST_PATH = 'forecast/daily/';
- export const WEATHER_ICONS = {
- day: {
- 'clear': 0xf00d,
- 'clouds': 0xf002,
- 'drizzle': 0xf009,
- 'rain': 0xf008,
- 'thunderstorm': 0x010,
- 'snow': 0xf00a,
- 'mist': 0xf0b6
- },
- night: {
- 'clear': 0xf02e,
- 'clouds': 0xf086,
- 'drizzle': 0xf029,
- 'rain': 0xf028,
- 'thunderstorm': 0xf02d,
- 'snow': 0xf02a,
- 'mist': 0xf04a
- },
- neutral: {
- 'temperature': 0xf055,
- 'wind': 0xf050,
- 'cloud': 0xf041,
- 'pressure': 0xf079,
- 'humidity': 0xf07a,
- 'rain': 0xf019,
- 'sunrise': 0xf046,
- 'sunset': 0xf052
- }
- };
- export const WIND_DIRECTIONS = [
- "North", "North-northeast", "Northeast",
- "East-northeast", "East", "East-southeast", "Southeast",
- "South-southeast", "South", "South-southwest", "Southwest",
- "West-southwest", "West", "West-northwest", "Northwest", "North-northwest"
- ];
The utilities module includes all sorts of utility functions: things like converting degrees to directions, determining a descriptive text for the wind speed, converting Kelvin to Celsius, and converting character codes into a character. You'll see how all of these functions are used later on in the pages.
- import constants = require('./constants');
- export function degreeToDirection(num) {
- var val= Math.floor((num / 22.5) + .5);
- return constants.WIND_DIRECTIONS[(val % 16)];
- }
- export function describeWindSpeed(speed) {
- if(speed < 0.3) {
- return 'calm';
- } else if(speed >= 0.3 && speed < 1.6) {
- return 'light air';
- } else if (speed >= 1.6 && speed < 3.4) {
- return 'light breeze';
- } else if (speed >= 3.4 && speed < 5.5) {
- return 'gentle breeze';
- } else if (speed >= 5.5 && speed < 8) {
- return 'moderate breeze';
- } else if(speed >= 8 && speed < 10.8) {
- return 'fresh breeze';
- } else if(speed >= 10.8 && speed < 13.9) {
- return 'strong breeze';
- } else if(speed >= 13.9 && speed < 17.2) {
- return 'moderate gale';
- } else if (speed >= 17.2 && speed < 20.8) {
- return 'gale';
- } else if (speed >= 20.8 && speed < 24.5) {
- return 'strong gale';
- } else if (speed >= 24.5 && speed < 28.5) {
- return 'storm';
- } else if (speed >= 28.5 && speed < 32.7) {
- return 'violent storm';
- } else if (speed >= 32.7 && speed < 42) {
- return 'hurricane force';
- }
- return 'super typhoon';
- }
- export function describeHumidity(humidity) {
- if (humidity >= 0 && humidity <= 40) {
- return 'very dry';
- } else if (humidity >= 40 && humidity <= 70) {
- return 'dry';
- } else if (humidity >= 85 && humidity <= 95) {
- return 'humid';
- }
- return 'very humid';
- }
- export function describeTemperature(temp) {
- var celsius = convertKelvinToCelsius(temp);
- if (celsius >= 0 && celsius < 7) {
- return 'very cold';
- } else if (celsius >= 8 && celsius < 13) {
- return 'cold';
- } else if (celsius >= 13 && celsius < 18) {
- return 'cool';
- } else if (celsius >= 18 && celsius < 23) {
- return 'mild';
- } else if (celsius >= 23 && celsius < 28) {
- return 'warm';
- } else if (celsius >= 28 && celsius < 32) {
- return 'hot';
- }
- return 'very hot';
- }
- export function convertKelvinToCelsius(celsius) {
- return celsius - 273.15;
- }
- export function getTimeOfDay() {
- var hour = (new Date()).getHours();
- var time_of_day = 'night';
- if(hour >= 5 && hour <= 18){
- time_of_day = 'day';
- }
- return time_of_day;
- }
- export function getIcons(icon_names) {
- var icons = icon_names.map((name) => {
- return {
- 'name': name,
- 'icon': String.fromCharCode(constants.WEATHER_ICONS.neutral[name])
- };
- });
- return icons;
- }
Navigation
The navigation module is a custom helper module which allows us to easily navigate between all the pages of the app. Open the common/navigation.ts file and add the following:
- import frame = require('ui/frame');
- export function getStartPage() {
- return 'pages/main/main';
- }
- export function goToForecastPage() {
- frame.topmost().navigate('pages/forecast/forecast');
- }
- export function goToMainPage() {
- frame.topmost().goBack();
- }
This uses the Frame module to navigate to other pages of the app. The getStartPage() method simply returns the location of the main app page. The goToForecastPage(), as the name suggests, allows the user to navigate to the forecast page.
When navigating in NativeScript, you need to have a reference of where you currently are. That's why you first need to call the topmost() function to get the current or uppermost page, and then the navigate() function to go to another page. This function accepts the path to the page where you want to go.
Requestor
The Requestor module performs the actual request to the OpenWeatherMap API. As mentioned in the Introduction to NativeScript article, NativeScript uses a JavaScript virtual machine to run JavaScript code. This means that we can also use functions that are available in the browser.
One such function is fetch, which allows us to make HTTP requests to a remote server. The parameter is the URL where you want to make the request. It returns a promise so we use then() to wait for the raw response. Note the use of the word "raw"; the fetch function returns the response with headers and other low-level information—that's why we need to call the json() function to get the actual JSON data. This will return another promise so we use then() one more time to get the actual object.
- export function get(url){
- return fetch(
- url
- ).then(function(response){
- return response.json();
- }).then(function(json){
- return json;
- });
- }
Alternatively, you can use the Http module, which is a more robust way of making HTTP requests in NativeScript.
Location Store
The location store serves as the storage for the location information. This allows us to update and get the current location from any file which imports this module.
- export var location;
- export function saveLocation(loc) {
- location = loc;
- }
- export function getLocation() {
- return location;
- }
(continue)
If you found this post interesting, follow and support us.
Suggest for you: