Angular 2 Components and Providers: Classes, Factories & Values

In a previous article, we looked at how to get data into and out of components using the @Input and @Output annotations. In this article, we’ll look at another fundamental aspect of Angular 2 components — their ability to use “providers.”
You may have seen “providers” in a list of properties you can use to configure components, and you might have realized that they allow you to define a set of injectable objects that will be available to the component. That’s nice, but it of course begs the question, “what is a provider?”
Answering that question gets us into an involved discussion of Angular 2’s Dependency Injection (DI) system. We may specifically cover DI in a future blog post, but it’s well covered in a series of articles by Pascal Precht, beginning with: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html. We’ll assume you are familiar with DI and Angular 2’s DI system in general, as covered in Pascal’s article, but in brief the DI system is responsible for:

Registering a class, function or value. These items, in the context of dependency injection, are called “providers” because they result in something. For example, a class is used to provide or result in an instance. (See below for more details on provider types.)
Resolving dependencies between providers — for example, if one provider requires another provider.
Making the provider’s result available in code when we ask for it. This process of making the provider result available to a block of code is called “injecting it.” The code that injects the provider results is, logically enough, called an “injector.”
Maintaining a hierarchy of injectors so that if a component asks for a provider result from a provider not available in its injector, DI searches up the hierarchy of injectors.

In the previous article, we included a diagram showing that components form a hierarchy beginning with a root component. Let’s add to that diagram to include the injectors and the resources (providers) they register:

Figure 1: Each component has its own injector that registers providers. Injectors create child injectors and a request for a provider starts with the local injector and searches up the injector hierarchy.
We can see from the above that while components form a downwards directed graph, their associated injectors have a two-way relationship: parent injectors create children (downwards) and when a provider is requested, Angular 2 searches the parent injector (upwards) if it can’t find the requested provider in the component’s own injector. This means that a provider with the same identifier at a lower level will shadow (hide) the same-named provider at a higher level.
What are Providers?
So, what are these “providers” that the injectors are registering at each level? Actually, it’s simple: a provider is a resource or JavaScript “thing” that Angular uses to provide (result in, generate) something we want to use:

A class provider generates/provides an instance of the class.
A factory provider generates/provides whatever returns when you run a specified function.
A value provider doesn’t need to take an action to provide the result like the previous two, it just returns its value.

Unfortunately, the term “provider” is sometimes used to mean both the class, function or value and the thing that results from the provider — a class instance, the function’s return value or the returned value.
Let’s see how we can add a provider to a component by creating a class provider using MyClass, a simple class that will generate the instance we want to use in our application.

Figure 2: A simple class with four properties. (Code screenshots are from Visual Studio Code)
Okay, that’s the class. Now let’s instruct Angular to use it to register a class provider so we can ask the dependency injection system to give us an instance to use in our code. We’ll create a component, ProvDemo_01.ts, that will serve as the root component for our application. We load this component and kick-off our application in the bootstrap.ts:

Figure 3: Our application’s bootstrap.ts file that instantiates the root component.
If the above doesn’t make sense, then take a look at our earlier post that walks through building a simple Angular 2 application. Our root component is called ProvDemo, and the repository contains several numbers versions of it. You can change the version that’s displayed by updating the line that imports ProvDemo above. Our first version of the root component looks like this:

Figure 4: CompDemo with MyClass imported, added to the providers array and used as a Type in the constructor arguments.
Adding the MyClass provider to this component is straightforward:

Import MyClass
Add it to the @Component providers property
Add an argument of type “MyClass” to the constructor.

Under the covers, when Angular instantiates the component, the DI system creates an injector for the component which registers the MyClass provider. Angular then sees the MyClass type specified in the constructor’s argument list and looks up the newly registered MyClass provider and uses it to generate an instance which it assigns to “myClass” (initial small “m”).
The process of looking up the MyClass provider and generating an instance to assign to “myClass” is all Angular. It takes advantage of the TypeScript syntax to know what type to search for but Angular’s injector does the work of looking up and returning the MyClass instance.
Given the above, you might conclude that Angular takes the list of classes in the “providers” array and creates a simple registry used to retrieve the class. But there’s a slight twist to make things more flexible. A key reason why a “twist” is needed is to help us write unit tests for our components that have providers we don’t want to use in the testing environment. In the case of MyClass, there isn’t much reason not to use the real thing, but if MyClass made a call to a server to retrieve data, we might not want to or be able to do that in the test environment. To get around this, we need to be able to substitute within ProvDemo a mock MyClass that doesn’t make the server call.
How do we make the substitution? Do we go through all our code and change every MyClass reference to MyClassMock? That’s not efficient and is a poor pattern for writing tests.
We need to swap out the provider implementation without changing our ProvDemo component code. To make this possible, when Angular registers a provider it sets up a map to associate a key (called a “token”) with the actual provider. In our example above, the token and the provider are the same thing: MyClass. Adding MyClass to the providers property in the @Component decorator is shorthand for:
providers: [ provide(MyClass, {useClass: MyClass} ]

This says “register a provider using ‘MyClass’ as the token (key) to find the provider and set the provider to MyClass so when we request the provider, the dependency injection system returns a MyClass instance.” Most of us are used to thinking of keys as being either numbers or strings. But in this case the token (key) is the class itself. We could have also registered the provider using a string for the token as follows:
providers: [ provide(“aStringNameForMyClass”, {useClass: MyClass} ]

So, how does this help us with testing? It means in the test environment we can override the provider registration, effectively doing:
provide(MyClass, {useClass: MyClassMock})

This associates the token (key) MyClass with the class provider MyClassMock. When our code asked the DI system to inject MyClass in testing, we get an instance of MyClassMock which can fake the data call. The net effect is that all our code remains the same and we don’t have to worry about whether the unit test will make a call to a server that might not exist in the test environment.
Continue reading %Angular 2 Components and Providers: Classes, Factories & Values%

Link: https://www.sitepoint.com/angular-2-components-providers-classes-factories-values/

Angular 2 Components: Inputs and Outputs

In this article, we’ll take a look a bit closer at Angular 2 components — how they’re defined, and how to get data into them and back out of them.
This is the second part in the Angular 2 series. You can read part one here. We covered the basic idea of components and decorators in an earlier article, and have specifically seen the @Component and @View decorators used to build an Angular application. This article dives in a bit deeper. However, we can’t cover everything about components in a single article, so future articles will take up other aspects of Angular components.
The code for this article and the other articles in the series is available as in the angular2-samples repo. You can also see the samples running at: http://angular2-samples.azurewebsites.net/.
Although it’s possible to write Angular 2 applications in ECMAScript 5 (the most common version of JavaScript supported by browsers), we prefer to write in TypeScript. Angular 2 itself is written in TypeScript and it helps us at development time and includes features that make it easier for us to define Angular components.
In particular, TypeScript supports decorators (sometimes referred to as “annotations”) which are used to declaratively add to or change an existing “thing”. For example, class decorators can add metadata to the class’s constructor function or even alter how the class behaves. For more information on decorators and the types of things you can do with them, see the proposal for JavaScript decorators. Angular 2 includes several decorators.
As we’ve covered in an earlier article, components are the key building block for Angular applications. They include a view, defined with HTML and CSS, and an associated controller that implements functionality needed by the view. The controller has three major responsibilities:

Manage the model, i.e. the application data used by the view
Implement methods needed by the view for things like submitting data or hiding/showing sections of the UI
Managing data related to the state of the view, such as which item in a list is currently selected.

Depending on your background, the above list might sound familiar. In fact, the Angular component controller sounds very much like the original definition of a view model as defined by John Gossman in 2005:
The term means “Model of a View”, and can be thought of as abstraction of the view, but it also provides a specialization of the Model that the View can use for data-binding. In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model. — Source (captured 11/27/2015)
Because components aren’t native JavaScript entities, Angular provides a way to define a component by pairing a constructor function with a view. You do this by defining a constructor function (in TypeScript it’s defined as a class) and using a decorator to associate your view with the constructor. The decorator can also set various configuration parameters for the component. This magic is accomplished using the @Component decorator we saw in the first article in this series.
Component Hierarchy
The above describes an individual component, but Angular 2 applications are actually made up of a hierarchy of components – they begin with a root component that contains as descendants all the components used in the application. Components are intended to be self-contained because we want to encapsulate our component functions and we don’t want other code to arbitrarily reach into our components to read or change properties. Also, we don’t want our component to affect another component written by someone else. An obvious example is CSS: if we set CSS for one component, we don’t want our CSS to “bleed out” to another components just as we don’t want other CSS to “bleed in” to our component.
At the same time, components do need to exchange data. In Angular 2, a component can receive data from its parent as long as the receiving component has specifically said it’s willing to receive data. Similarly, components can send data to their parents by trigger an event the parent listens for. Let’s look at how the component hierarchy behaves. To begin, we can draw it as follows:

Each box is a component and technically this representation is called “graph” — a data structure consisting of nodes and connecting “edges.” The arrows represent the data flow from one component to another, and we can see that data flows in only one direction — from the top downwards to descendants. Also, note there are no paths that allow you to travel from one node, through other nodes and back to the one where you started. The official name for this kind of data structure is a “directed acyclic graph” — that is, it flows in only one direction and has no circular paths in it.
This kind of structure has some important features: it’s predictable, it’s simple to traverse, and it’s easy to see what’s impacted when a change is made. For Angular’s purposes, when data changes in one node, it’s easy to find the downstream nodes that could be affected.
A simple example of how this might be used is a table with rows containing customers and information about them, in which a table component contains multiple individual row components that represent each customer. The table component could manage a record set containing all the customers and pass the data on an individual customer to each of the row components it contains.
This works fine for simply displaying data, but in the real world data will need to flow the other way — back up the hierarchy — such as when a user edits a row. In that case, the row needs to tell the table component that the data for a row has changed so the change can be sent back to the server. The problem is that, as diagrammed above, data only flows down the hierarchy, not back up. To ensure we maintain the simplicity of one-way data flow down the hierarchy, Angular 2 uses a different mechanism for sending data back up the hierarchy: events.

Now, when a child component takes an action that a parent needs to know about, the child fires an event that’s caught by the parent. The parent can take any action it needs which might include updating data that will, through the usual one-way downwards data flow, update downstream components. By separating the downward flow of data from the upwards flow of data, things are kept simpler and data management performs well.
Continue reading %Angular 2 Components: Inputs and Outputs%

Link: https://www.sitepoint.com/angular-2-components-inputs-outputs/

The Difference Between AngularJS, Angular 2, Angular 4

Angular is considered one of the best open-source JavaScript frameworks. Google’s Angular team released Angular 2 as a complete makeover of its original Angular 1 framework. For those of you who are still learning Angular frameworks, this blog will offer a comparison of Angular 1 (AngularJS), Angular 2, and Angular 4
Architecture
The architecture of Angular 1 is based on the Model View Controller.

Link: https://dzone.com/articles/learn-different-about-angular-1-angular-2-amp-angu?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Learning Angular: Everything You Need to Get Started

Whether it’s AngularJS 1.X – a framework, or Angular – a platform, Google’s Angular project has taken over the web. Here’s a collection of articles, projects and courses that’ll help you get to grips with the powerful front-end tool.
But if you’re starting from scratch, and you’d like to go from zero to expert fast, a course recommendation. For expert-led online Angular training courses you can’t go past Ultimate Angular by Todd Motto. Try his courses here [ultimateangular], and use the code SITEPOINT to get 25% off and to help support SitePoint.
Introductions and Comparisons

Angular version naming got a little complicated this year, here are the official naming conventions for specific versions of the platform [angularjs], which we’ve tried to follow here and elsewhere on the site.
How to decide between React and Angular [sitepoint].

Fundamentals

How to create a single-page app with AngularJS and the WordPress REST API [sitepoint].
A guide to managing state in Angular apps with ngrx/store [sitepoint].
Managing state in Angular apps [blog.nrwl].
Persisting state in AngularJS [sitepoint].
How to build maintainable Angular apps [medium/curated-by-versett].
How to develop apps with Angular mockbackend [sitepoint].
A community-drive collection of best practices and style guidelines for AngularJS [github/mgechev].

Testing

A guide to testing your services with Angular [corinnekrych.blogspot].
How to test your Angular component [corinnekrych.blogspot].

Authentication

Angular authentication with JSON [angularjs.blogspot].
And easy Angular authentication with Auth0 [sitepoint].

Slightly More Advanced

Developing an app with Angular 2+ and the Angular CLI [sitepoint]
An anatomy of a large Angular application [medium]
Creating Progressive Web Apps with Angular [medium]
Improving Angular performance with one line of code [blog.upstate]
Building Angular apps at scale [medium]
Track device geolocation in NativeScript Angular mobile applications [thepolyglotdeveloper]
Deploy your own REST API using mLab and Heroku [sitepoint]

Projects
You’ve got the basics – and perhaps even a little bit more. Here are some projects to take on to put that knowledge into practice.
Continue reading %Learning Angular: Everything You Need to Get Started%

Link: https://www.sitepoint.com/learning-angular-everything-you-need-to-get-started/

An Introduction to Component Routing with Angular Router

This article is part 4 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

Part 0— The Ultimate Angular CLI Reference Guide
Part 1— Getting our first version of the Todo application up and running
Part 2— Creating separate components to display a list of todo’s and a single todo
Part 3— Update the Todo service to communicate with a REST API
Part 4— Use Angular router to resolve data
Part 5— Add authentication to protect private content

In part one we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine but, unfortunately, the whole app was crammed into a single component.
In part two we examined a more modular component architecture and learned how to break this single component into a structured tree of smaller components that are easier to understand, reuse and maintain.
In part three we updated our application to communicate with a REST API backend using RxJS and Angular’s HTTP service.
In this part, we will introduce Angular router and learn how it can update our application when the browser URL changes and vice versa. We will also learn how we can update our application to resolve data from our backend API using the router.

Don’t worry! You don’t need to have followed part one, two or three of this tutorial, for four to make sense. You can simply grab a copy of our repo, checkout the code from part three, and use that as a starting point. This is explained in more detail below.

Up and Running
Make sure you have the latest version of the Angular CLI installed. If you don’t, you can install it with the following command:
npm install -g @angular/cli@latest

If you need to remove a previous version of the Angular CLI, you can:
npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that, you’ll need a copy of the code from part three. This is available at https://github.com/sitepoint-editors/angular-todo-app. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.
The code that we ended with in part three and that we start with in this article is tagged as part-3. The code that we end this article with is tagged as part-4.

You can think of tags like an alias to a specific commit id. You can switch between them using git checkout. You can read more on that here.

So, to get up and running (the latest version of the Angular CLI installed) we would do:
git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
git checkout part-3
npm install
ng serve

Then visit http://localhost:4200/. If all is well, you should see the working Todo app.
A quick recap
Here is what our application architecture looked like at the end of part 3:

In this article we will:

learn why an application may need routing
learn what a JavaScript router is
learn what Angular router is, how it works and what it can do for you
set up Angular router and configure the routes for our application
create a resolver to fetch the todo’s from our REST API
update our application to fetch the todo’s using our new resolver

By the end of this article, you will understand:

when and why your application may need routing
the difference between routing on the server and routing in the browser
what Angular router is and what it can do for your application
how to set up Angular router
how to configure routes for your application
how to tell Angular router where to place components in the DOM
how to gracefully handle unknown URLs
what a resolver is and what it can be used for
how to use a resolver to resolve data using Angular router

So, let’s get started!
Why routing?
In its current state, our web application does not take the browser URL into account.
We access our application through one URL e.g. http://localhost:4200 and our application is not aware of any other URLs such as http://localhost:4200/todos.
Most web applications need to support different URLs to navigate users to different pages in the application. That is where a router comes in.
In traditional websites, routing is handled by a router on the server:

a user clicks a link in the browser, causing the URL to change
the browser sends an HTTP request to server
the server reads the URL from the HTTP request and generates an appropriate HTTP response
the server sends the HTTP response to the browser

In modern JavaScript web applications, routing is often handled by a JavaScript router in the browser.
What is a JavaScript router?
In essence, a JavaScript router does 2 things:

update the web application state when the browser URL changes
update the browser URL when the web application state changes

JavaScript routers make it possible for us to develop Single Page Applications (SPA’s).
A Single Page Application is a web application that provides a user experience similar to a desktop application. In a Single Page Application, all communication with a back-end occurs behind the scenes.
When a user navigates from one page to another, the page is updated dynamically without reload, even if the URL changes.
There are many different JavaScript router implementations available.
Some of them are specifically written for a certain JavaScript framework such as Angular, ember, React, Vue.js, aurelia, etc. Other implementations are built for generic purposes and are not tied to a specific framework.
What is Angular router?
Angular router is an official Angular routing library, written and maintained by the Angular Core Team.
It is a JavaScript router implementation that is designed to work with Angular and is packaged as @angular/router.
First of all, Angular router takes care of the duties of a JavaScript router:

it activates all required Angular components to compose a page when a user navigates to a certain URL
it lets users navigate from one page to another without page reload
it updates the browser’s history so the user can use the back and forward buttons when navigating back and forth between pages

In addition, Angular router allows us to:

redirect a URL to another URL
resolve data before a page is displayed
run scripts when a page is activated or deactivated
lazy load parts of our application

In this article, we will learn how to set up and configure Angular router, how to redirect a URL and how to use Angular router to resolve todo’s from our back-end API.
In the next article, we will add authentication to our application and use the router to make sure some of the pages can only be accessed when the user is signed in.
How Angular Router Works
Before we dive into the code, it is important to understand how Angular router operates and the terminology it introduces.
When a user navigates to a page, Angular router performs the following steps in order:

it reads the browser URL the user wants to navigate to
it applies a URL redirect (if one is defined)
it figures out which router state corresponds to the URL
it runs the guards that are defined in the router state
it resolves the required data for the router state
it activates the Angular components to display the page
it manages navigation and repeats the steps above when a new page is requested

To accomplish its tasks, Angular router introduces the following terms and concepts:

router service: the global Angular router service in our application
router configuration: definition of all possible router states our application can be in
router state: the state of the router at some point in time, expressed as a tree of activated route snapshots
activated route snapshot: provides access to the URL, parameters, and data for a router state node
guard: script that runs when a route is loaded, activated or deactivated
resolver: script that fetches data before the requested page is activated
router outlet: location in the DOM where Angular router can place activated components

Don’t worry if the terminology sounds overwhelming. You will get used to the terms as we tackle them gradually in this series and as you gain more experience with Angular router.
An Angular application that uses Angular router only has one router service instance; It is a singleton. Whenever and wherever you inject the Router service in your application, you will get access to the same Angular router service instance.
For a more in-depth look at Angular routing process, make sure to check out the 7-step routing process of Angular router navigation.
Enabling Routing
To enable routing in our Angular application, we need to do 3 things:

create a routing configuration that defines the possible states for our application
import the routing configuration into our application
add a router outlet to tell Angular router where to place the activated components in the DOM

So let’s start by creating a routing configuration.
Creating the routing configuration
To create our routing configuration, we need a list of the URLs we would like our application to support.
Currently, our application is very simple and only has one page that shows a list of todo’s:

/: show list of todo’s

which would show the list of todo’s as the homepage of our application.
However, when a user bookmarks / in their browser to consult their list of todo’s and we change the contents of our homepage (which we will do in part 5 of this series), their bookmark would no longer show their list of todo’s.
So let’s give our todo list its own URL and redirect our homepage to it:

/: redirect to /todos
/todos: show list of todo’s

This provides us with two benefits:

when users bookmark the todos page, their browser will bookmark /todos instead of /, which will keep working as expected, even if we change the home page contents
we can now easily change our homepage by redirecting it to any URL we like, which is convenient if you need to change your homepage contents regularly

The official Angular style guide recommends storing the routing configuration for an Angular module in a file with a filename ending in -routing.module.ts that exports a separate Angular module with a name ending in RoutingModule.
Our current module is called AppModule, so we create a file src/app/app-routing.module.ts and export our routing configuration as an Angular module called AppRoutingModule:
Continue reading %An Introduction to Component Routing with Angular Router%

Link: https://www.sitepoint.com/component-routing-angular-router/