Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for TypeScript

October 18, 2016

Angular 2: Getting Started Course Update

This post identifies the changes to the “Angular 2: Getting Started” Pluralsight course from its first release on April 1st, 2016 to its update October 18th, 2016.

Angular 2 first appeared around June of 2015 as alpha.27. The first beta release of Angular 2 was December 12, 2015, a great time to start on an Angular 2 getting started course. The first release of the “Angular 2: Getting Started” course was on April 1st, 2016. The code examples for the course were valid through Angular beta.15. From that time until release, Angular underwent numerous changes … some, such as the new router and the introduction of Angular modules, were significant.

Angular 2.0.0 was released on September 14th, 2016, so that was a great time to update the “Angular 2: Getting Started” course. The changes made to each module of the course are outlined below.

If you have already watched the course and want to minimize which modules to re-watch, I’d suggest modules 2, 10, 11, and 12. That would provide the basics on Angular modules (NgModule) and the new router.

Module 1: Introduction

  • Introduced Angular modules.
  • Updated Course Outline.

Module 2: First Things First

  • Demoed how to get a more current version of npm.
  • Revised setup steps including the application’s root Angular module.
  • Updated discussion of AngularCli.
  • Updated demos for setting up Angular 2.
  • Enhanced discussion in “About Modules” regarding the difference between ES modules and Angular modules.

Module 3: Introduction to Components

  • Updated demos for new import statements (import from @angular/… instead of angular2/…)
  • A first cut of the app.component.ts is now included as part of the starter files. This changes some of the initial steps when building the app.component.ts file.
  • Added a callout to point out the use of the back tick (not quotes) for defining the inline template.
  • Bootstrapping process now includes the application’s root Angular module.
  • Additional checklist for resolving issues when coding along.

Module 4: Templates, Interpolation, and Directives

  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Added steps to update the application’s root Angular module (AppModule).
  • Added information on how an Angular module defines the boundary or context within which the component resolves its directives and dependencies.
  • Added a demonstration of a common Angular error and how to fix it.
  • Updated the ngFor syntax to match the released syntax using the let keyword instead of #.

Module 5: Data Binding & Pipes

  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Added information on adding FormsModule to an Angular module so the template can use ngModel for two-way binding.

Module 6: More on Components

  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Updated the code for the pipe transform to match the new transform signature.
  • Added a step to add the custom pipe to an Angular module.
  • Added a clip on using component-relative paths by setting module Ids.

Module 7: Building Nested Components

  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Added a step to add the nested component to an Angular module.

Module 8: Services and Dependency Injection

  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Mentioned how service can be registered in an Angular module.

Module 9: Retrieving Data Using Http

  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Enhanced discussion of Observables.
  • Enhanced the comparison between Promises and Observables.
  • Removed the setup clip since these setup steps are no longer valid.
  • Added a step to add Http to an Angular module.
  • Separated out the exception handling to its own clip.

Module 10: Navigation and Routing Basics

  • Divided this course module into two modules: 10 and 11.
  • Major modifications throughout to change to the current router.
  • Expanded on the details for how routing works.
  • Enhanced the discussion of Html 5 vs hash style routes.
  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Added steps to add the remaining components to an Angular module.

Module 11: Navigation and Routing Additional Techniques

  • This new module is the second half of the prior module.
  • Major modifications throughout to change to the current router.
  • Updated demos for new import statements (import from @angular/… instead of angular2/…).
  • Added a clip on route guards.

Module 12: Angular Modules

  • This new module is all about Angular modules. It covers:
    • The definition and purpose of an Angular module.
    • Understanding the Angular module metadata and its many rules.
    • Refactoring the sample application and creating a feature module.
    • Minimizing repetition by creating a shared module.
    • Reexamining the root application module (AppModule).
    • A look at building separate routing modules.
    • And summarizing options for your Angular module architecture.

Module 13: Angular 2 Setup Revisited

  • Updated the demos to the Angular 2 release setup files.
  • Added discussion of the systemjs.config.js file.
  • Added discussion of the bootstrapping process differences for the Just in Time (JiT) compiler vs the Ahead of Time (AoT) compiler.
  • Added discussion of the Angular CLI.

Module 14: Final Words

  • Minor wording changes.

Enjoy!

May 11, 2016

Angular 2: Getting Started with a Visual Studio 2015 TypeScript Project

My “Angular 2: Getting Started” course on Pluralsight details how to get started with Angular 2. To provide guidance that works on any platform (Windows, OS X, and Linux), the course uses Visual Studio Code as the editor. However, there are many developers that prefer to use Angular 2 with Visual Studio 2015.

The biggest challenge in providing guidance for using Angular 2 with Visual Studio 2015 is that there are too many options as outlined in this prior post. This post focuses on using Angular 2 with a Visual Studio 2015 TypeScript project.

For this technique, we’ll cover how to set up and run the “Angular 2: Getting Started” files using a TypeScript project in Visual Studio 2015.

1. Download the starter files from my GitHub repo: https://github.com/DeborahK/Angular2-GettingStarted

    If you are not familiar with using GitHub, just click on the “Download ZIP” button as shown below. Then unzip the files.

image_thumb3

2. Open Visual Studio 2015 and create a new project: File | New | Project.

3. Select the TypeScript project template and name the project “APM” for Acme Product Management.

image_thumb7

4. This creates several TypeScript sample files. Delete app.css, app.ts, and index.html.

image_thumb10

5. In file explorer, open the cloned or unzipped `APM – Start` folder if you want to start with the project starter files. Open the `APM – Final` folder if you want to work with the final files from the course.

image_thumb13

image_thumb16

6. Copy all of the files from within the folder shown above (except the .vscode folder) to the APM project file you just created with Visual Studio.

image_thumb20

7. Click the “Show All Files” button in the toolbar of Solution Explorer.

image_thumb27

8. Select to include the api and app folders and the index.html, package.json, tsconfig.json, and typings.json files into the project. If desired, click “Show All Files” again to hide the remaining files.

image_thumb33

9. Right-click on the package.json file and select: Restore Packages

image_thumb36

10. Open the Output window (View | Output) to watch Visual Studio 2015 run npm and install Angular 2 and its dependencies.

So even through we are using a Visual Studio 2015 menu option (Restore Packages), Visual Studio is running the Node Package Manager (npm) to install all of the packages defined in the package.json file.

image_thumb40

11. If npm finishes successfully, it should appear like this (see below) in the Output window.

image_thumb43

12. Right-click on index.html and select Set As Start Page.

image_thumb46

NOTE: There is an intentionally missing component (because we have not created it yet!). When running in VS Code, the application runs even though this file is missing. In Visual Studio 2015, the compile will fail and the application won’t run. To successfully compile the code, open main.ts and comment out the contents of this file. (Just be sure to uncomment them after we build the app.component.)

13. Press F5 to run and the application appears in the selected browser.

HOWEVER … you won’t be able to edit and continue. And if you edit and try to refresh the browser, you will most likely see a 404 message.

I have not yet figured out the magic required to provide edit and continue using Visual Studio 2015 directly … but you can get edit and continue if you stop debugging and run the application using a script instead of F5 following these additional steps:

14. Display the Package Manager Console (View | Other Windows | Package Manager Console).

15. Type `cd APM` in the Package Manager Console to change to the directory containing the APM project.

NOTE that if you used a different directory name for your project, type that instead. And if you have a space in the name, it will need to be enclosed in quotes: cd “APM – Start”

16. Type ‘npm start’ into the Package Manager Console.

This will launch your default browser and watch for changes. You can then edit any of the project files (AND SAVE!). The browser will then update automatically and reflect your changes.

By following the above steps, you can follow along with the course using Visual Studio 2015 instead of VS Code. Just be sure to follow steps 14-16 above each time you reopen the project to restart the script that watches for changes and refreshes the browser.

It would be great to hear from you on whether these steps worked for you. Follow me on twitter: @deborahkurata

Enjoy!

September 4, 2015

Use TypeScript to Prepare for Angular 2

If you are developing now in Angular 1.x with an eye toward Angular 2, the best thing you can do is to write your Angular code with TypeScript. Angular 1.x code you write in TypeScript today will look very similar to code you will write in Angular 2 tomorrow (not literally tomorrow!).

At a recent Angular conference, the members of the Angular team from Google stated that one of the best ways to code now in Angular 1.x in preparation for Angular 2 is to use TypeScript.

What is TypeScript?

image

TypeScript is an open-source programming language that is:

  • A superset of JavaScript
    • Including all of the current JavaScript syntax, plus much more.
    • Any valid JavaScript code is valid TypeScript code. And as such, TypeScript works with all existing JavaScript frameworks, including Angular.
  • TypeScript transpiles to plain JavaScript
    • So we can deploy the resulting JavaScript files for our Angular application just as we do now.
    • And the resulting files execute in any of today’s browsers on any OS.
    • Plus there is no runtime overhead of using TypeScript because all of the types evaporate and the TypeScript-only syntax is replaced … leaving only pure JavaScript.
  • TypeScript allows us to define strong types
    • Editor tooling, such as the new Visual Studio Code editor, use these types for static type checking of our code during development
    • This makes development, debugging, and refactoring easier.
    • Plus it clarifies the developer’s intent. For example, we can define that a function is meant to take in a string. Not a number, not an object, just a string.
  • And TypeScript provides class-based object-oriented programming techniques.
    • So we can optionally think of our code in terms of objects with properties and methods.
    • And the TypeScript compiler transpiles the classes into JavaScript functions.

Here is the code for an Angular controller, written using the class-based object-oriented programming techniques available in TypeScript.

AngularWTypeScript_Code

To learn more about using Angular with TypeScript, check out the Pluralsight course: “Angular with TypeScript

AngularWTypeScript

Enjoy!

August 12, 2015

Automatic Compilation in VS Code for TypeScript

Filed under: TypeScript,VS Code @ 2:19 pm
Tags: ,

By default, when you use VS Code with a TypeScript project, you need to use Ctrl+Shift+B (or Cmd+Shift+B on a mac) to build the application and transpile the TypeScript to JavaScript. But there is a way to make this process more seamless.

To set up VS Code to watch for changes and transpile automatically requires two steps:

1) Modify the tsconfig.json file for the project.

2) Run the TypeScript compiler on the folder for the project.

Let’s look at both of these steps in detail.

Modify the tsconfig.json File

The tsconfig.json file configures TypeScript for your project. In the tsconfig.json file you can define compiler options, such as the version of JavaScript you’d like the transpiler to use. The TypeScript code is then transpiled to the selected version of TypeScript.

To configure VS Code for automatic compilation, you need to add a watch property here:

{
    “compilerOptions”: {
        “target”: “ES5”,
       “watch”: true
    }
}

NOTE: The intellisense does not seem to know about the “watch” option. So you won’t see it in the list of available compiler options. But it does work.

Run the TypeScript Compiler

You can manually run the TypeScript compiler from within VS Code by using Ctrl+Shift+B (or Cmd+Shift+B). Alternatively, you can manually run the TypeScript compiler from the command window (also called a terminal).

1) Right-click on the index.html file in the VS Code Explore pane and select Open in Console.

This opens a command window defaulted to the current project directory.

2) Type tsc.

Typing tsc (for TypeScript compiler) immediately transpiles all of the TypeScript code in the directory (and subdirectories) to JavaScript. Without the “watch” setting, if you later make changes to the TypeScript code, you have to re-run the tsc command to transpile the changes.

image

HOWEVER, if you have the watch compiler option set to true as shown in the code example above, running tsc here produces a different result. In this case, the TypeScript compiler will immediately transpile all of the TypeScript code in the directory (and subdirectories). But then, it will start watching for changes. Any change it sees to the files in the directory will automatically be transpiled. Notice in the screen shot below that it watched me make 3 changes and compiled after each of them.

image

If you leverage VS Code’s AutoSave feature, and turn on the watch following the two steps detailed above, then the TypeScript compiler will transpile your TypeScript files every time you make a change.

Enjoy!

For more information on other techniques when building an Angular application with TypeScript, check out my Pluralsight course: “Angular with TypeScript”

Thanks to Greg who posted this suggestion to the Discussion forum for my Pluralsight course.

Angular Custom Services in TypeScript: Factory vs Service

Filed under: AngularJS,TypeScript @ 1:14 pm
Tags: , , ,

In my prior post (http://bit.ly/DeborahK_AngularServices) I outlined the difference between the factory pattern and service pattern when building a custom Angular service with JavaScript. In this post we’ll look at the differences when the Angular custom service is written in TypeScript.

Angular Custom Service

The basic code to create an Angular custom service in TypeScript is the same for both the factor pattern and the service pattern.

Here is an example of a simple custom service written in TypeScript, missing only the Angular module registration:

module app.common {
    export interface IHelloService {
        sayHello(text: string): string;
        sayGoodbye(text: string): string
    }

    export class HelloService implements IHelloService {
        sayHello(text: string): string {
            return “Hello ” + text;
        };
        sayGoodbye(text: string): string {
            return “Goodbye ” + text;
        };
    }
    <Module Registration Here>
}

This code begins with a TypeScript module. The TypeScript module encapsulates the code within an Immediately Invoked Function Expression (IIFE) and provides a clean namespace for the service.

The interface defines the intent of the service. The service intends to provide a sayHello method and a sayGoodbye method. Both take in a string parameter and return a string.

The service class is exported so that it can be used from any other Angular code, such as an Angular controller. The class implements the defined interface, thereby committing to implement every property and method defined in that interface. In our case, it is committing to implement the two methods.

The primary difference between the factory pattern and service pattern when building an Angular service with TypeScript is the module registration. Let’s take a look at how that registration is different.

Service Pattern

When using the service pattern, the TypeScript code to register the service with an Angular module is straightforward.

Simply call the service method:

angular
        .module(“helloWorld”)
        .service(“helloService”,
                         HelloService);

Insert the above code into the service example in place of <Module Registration Here> and you have a working service using the service pattern.

Factory Pattern

Using the factory pattern, the registration code is a little more complex.

As shown in the prior post (http://bit.ly/DeborahK_AngularServices), an Angular factory returns an object. When building the service with a TypeScript class, a class itself cannot return an object. Properties and methods of the class can return an object, but the class itself cannot.

So when using the factory pattern with TypeScript, the trick is to define a function that creates an instance of the service and returns an object. The code for that looks like this:

function factory(): HelloService {
    return new HelloService();
}

angular
    .module(“helloWorld”)
    .factory(“helloService”,
                     factory);

Insert the above code into the service example in place of <Module Registration Here> and you have a working service using the factory pattern.

Enjoy!

For more information on this and many other techniques when building an Angular application with TypeScript, check out my Pluralsight course: “Angular with TypeScript”

AngularWTypeScript2

© 2017 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs