Hands-On TypeScript for C# and .NET Core Developers
eBook - ePub

Hands-On TypeScript for C# and .NET Core Developers

Transition from C# to TypeScript 3.1 and build applications with ASP.NET Core 2

  1. 460 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On TypeScript for C# and .NET Core Developers

Transition from C# to TypeScript 3.1 and build applications with ASP.NET Core 2

About this book

Discover how TypeScript allows you to build modern client-rich applications, thanks to its object-oriented capabilities and third-party tools like Angular and Web APIs

Key Features

  • Make a seamless transition to using TypeScript 3.1 in your development stack
  • Work with TypeScript 3.1 in your ASP.NET Core projects to build rich applications that are easy to maintain
  • Build, test, and integrate your own TypeScript library in real-world projects

Book Description

Writing clean, object-oriented code in JavaScript gets trickier and complex as the size of the project grows. This is where Typescript comes into the picture; it lets you write pure object-oriented code with ease, giving it the upper hand over JavaScript. This book introduces you to basic TypeScript concepts by gradually modifying standard JavaScript code, which makes learning TypeScript easy for C# ASP.NET developers.

As you progress through the chapters, you'll cover object programming concepts, such as classes, interfaces, and generics, and understand how they are related to, and similar in, both ES6 and C#. You will also learn how to use bundlers like WebPack to package your code and other resources. The book explains all concepts using practical examples of ASP.NET Core projects, and reusable TypeScript libraries. Finally, you'll explore the features that TypeScript inherits from either ES6 or C#, or both of them, such as Symbols, Iterables, Promises, and Decorators.

By the end of the book, you'll be able to apply all TypeScript concepts to understand the Angular framework better, and you'll have become comfortable with the way in which modules, components, and services are defined and used in Angular. You'll also have gained a good understanding of all the features included in the Angular/ASP.NET Core Visual Studio project template.

What you will learn

  • Organize, test, and package large TypeScript code base
  • Add TypeScript to projects using TypeScript declaration files
  • Perform DOM manipulation with TypeScript
  • Develop Angular projects with the Visual Studio Angular project template
  • Define and use inheritance, abstract classes, and methods
  • Leverage TypeScript-type compatibility rules
  • Use WebPack to bundle JavaScript and other resources such as CSS to improve performance
  • Build custom directives and attributes, and learn about animations

Who this book is for

If you're a C# or.NET developer looking for an easy accessible way of learning TypeScript, this book is for you.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
No, books cannot be downloaded as external files, such as PDFs, for use outside of Perlego. However, you can download books within the Perlego app for offline reading on mobile or tablet. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Hands-On TypeScript for C# and .NET Core Developers by Francesco Abbruzzese in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in C#. We have over one million books available in our catalogue for you to explore.

Information

Navigation and Services

Up to now, we have learned how to build applications that perform simple tasks and whose content can be navigated by loading a few components on the HTML page. However, the main purpose of single page application frameworks, such as Angular, is the implementation of complex business applications that exchange non-trivial quantities of data with a remote server. In such complex applications, acceptable user interface and performance can only be ensured with complex navigation patterns, as well as with efficient data exchange techniques.
This chapter explains how to enable components to perform complex tasks, such as communicating with the server, with the help of service classes automatically injected in their constructors. It also explains how to mount and test a complete application with complex navigation patterns that optimize both performance and application loading time by means of lazy loading Angular modules. The reader is required to practice all concepts learned by adding new code to the one produced so far, and by modifying existing client-server communications.
More specifically, you will learn the following topics:
  • Defining services and using them with Dependency Injection
  • Using Angular HTTP Client to define services
  • Defining SPA pages with routing and lazy loading
  • Using Angular testing frameworks

Technical requirements

The technical requirements for this chapter are as follows:
  • Visual Studio 2017, with the latest ASP.NET Core tools
  • Visual Studio TypeScript SDK
  • A version of Angular CLI installed globally (Version 6 or above)
For the installation of Angular CLI, please refer to the Technical requirements section of Chapter 10, Angular ASP.NET Core Project Template.
All the code used in this chapter can be downloaded from the following GitHub link: https://github.com/PacktPublishing/Hands-On-TypeScript-for-CSharp-and-.NET-Core-Developers.
Check out the following video to see the Code in Action: http://bit.ly/2AzyHGs.

Services and Dependency Injection

Application modularity requires that chunks of code performing the same task in several Angular components be factored out into separate classes. Actually, to improve software maintainability, it is best practice to factor out all code chunks that might be useful to other Angular component classes even when these other components have not yet been created. As a consequence, Angular components should only contain code that is specific to their internal peculiarities, that is, the code that defines their interaction with the user. Code that defines business logic, and localization rules, as well as code that handles application-level services, must be factored out in various specialized classes, which are usually referred to as services.
Thus, for instance, the code that takes care of retrieving and updating products from a database located on the server should be grouped in dedicated service classes. In general, the whole business logic that updates and retrieves data handled by a component must be factored out in service classes. Also, general-purpose error messages should be factored out in services, since they are application-level resources.
The simple approach of letting each component create all the services they need has several drawbacks:
  • Service settings usually depend on the overall application state, which is unknown to each single component. Therefore, in general, components should be able to create services with the correct settings, so forcing them to do it would break application modularity, and would yield spaghetti code.
    Services that depend on the context are more common than they might appear, since possible contexts also include component testing. During unit testing, it is very difficult to arrange fake servers and other application parts that behave as required by each test. Therefore, when testing components, fake services are used that provide the data needed by the tests without actually interacting with a server and/or other application parts.
  • Service creations may be expensive operations, so it is convenient that several components share the same service instance. Moreover, instance sharing becomes a necessity when service instances contain state information that must be shared among components.
    Implementing shared instances with static properties directly handled by the components breaks application modularity, creates problems during testing, and is likely to yield hard-to-find bugs during software maintenance because access to the static properties containing the shared services are spread throughout the code: they are hidden inputs/outputs that are difficult to track, and difficult to prepare, during testing.
Dependency Injection (DI) was conceived to overcome all of the aforementioned drawbacks. According to the DI paradigm, service instances are handled by a hierarchy of containers. Each container has a record for each service it can provide.
This record contains information on the following:
  • How to create each service in a way that can be dependent on the overall application state?
  • If the service is a singleton, or if a new instance is created each time the service is requested. When a service is not found in a container, it is searched up in the container hierarchy until it reaches the root. Thus, the structure of the hierarchy defines which requests share the same singletons, and which requests share the same service creation strategy.
Angular, like all frameworks relying on DI, allows the automatic injection of services in class constructors. Some DI engines also allow services to be injected into adequately tagged properties. All DI frameworks allow the recursive injection of services, that is, services mentioned in the constructor of other services are automatically created and injected into the service constructor, and this process is recursive. All requests caused by the recursion on the same initial request are resolved in the same container of the initial request (moving up in the containers hierarchy if the service is not found).
Angular containers are called service injectors, or simply injectors, and they contain only singletons; in other words, each service instance, once created in a container, is reused for all subsequent requests issued to that container. This is not an actual limitation, since Angular is a client-side framework, so singleton here means unique to the user session. Moreover, injector hierarchy also includes injectors associated with each component instance, so service instances placed there are unique, but only in the lifetime of that component instance.
Angular injects services in the constructors of all Angular building blocks: components, directives, pipes, and services themselves. Each parameter in the constructor of these class types is interpreted as a service retrieved in the current container, and injected into the constructor before creating an instance. The next subsection explains how the hierarchy of Angular injectors is organized and how to determine the current injector when components, directives, and pipes are created. Services mentioned in the constructor of other services use the same container as the initial request that caused their creation.

Angular injectors' hierarchy

Angular contains a unique platform injector that is populated when the application is bootstrapped. This injector contains services used by the framework itself, and other services that the developer can add in main.ts where the application is bootstrapped. The code scaffolded by the Visual Studio Angular template adds a service that returns the application base URL, as follows:
export function getBaseUrl() {
return document.getElementsByTagName('base')[0].href;
}
const providers = [
{ provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];
platformBrowserDynamic(providers).bootstrapModule(AppModule)
.catch(err => console.log(err));
In this case, the service is indexed by the string token BASE_URL. The singleton is itself a string that is computed by a factory function. The following subsection discusses in detail all the options Angular offers to index and select services, and to create their singleton instances.
Other injectors are also added to all instances of Angular modules and components. The records that describe all services provided by each injector are called service providers, or simply providers. They are added to the providers array property of the @NgModule and @Component decorators:
@NgModule({
...
providers: [
{...},
{...}
...
],
...
})
...
@Component({
...
providers: [
...
],
...
})
These injectors have the same lifetime of modules and component instances of which they are part. Module instances live until the end of the application. Accordingly, injectors associated with module instances span the entire lifetime of the application. Component instances and their injectors have a shorter lifetime, since they are removed from the DOM when the user navigates to other content, or when some DOM parts are destroyed for other reasons. For instance, components contained in an *ngIf directive are removed with all their descendants when the *ngIf condition becomes false. Components contained in an *ngFor instance are destroyed when the enumerable bound to the directive changes. Components contained in a <router-outlet> instance are removed with all their descendants when a router loads a different component instance in that <router-outlet>. Moreover, while modules are singletons, components may be instantiated several times in different places. Thus, injectors associated with components have a lifetime that is limited to the lifetime of each component instance, and that is usually shorter than the lifetime of the application.
All services added to each x module are merged into the application main module injector (app.component.ts) when the module is imported. Thus, when the application starts, there is just one a...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. Packt Upsell
  5. Contributors
  6. Preface
  7. Introduction to TypeScript
  8. Complex Types and Functions
  9. DOM Manipulation
  10. Using Classes and Interfaces
  11. Generics
  12. Namespaces and Modules
  13. Bundling with WebPack
  14. Building TypeScript Libraries
  15. Decorators and Advanced ES6 Features
  16. Angular ASP.NET Core Project Template
  17. Input and Interactions
  18. Angular Advanced Features
  19. Navigation and Services
  20. Assessments
  21. Other Books You May Enjoy