Angularjs web service

An Angular Application is nothing more than a tree of Components.

How Angular Works

In this chapter, we’re going to talk about the high-level concepts of Angular. We’re going to take a step back so that we can see how all the pieces fit together.s

If you’ve used AngularJS 1.x, you’ll notice that Angular has a new mental-model for building applications. Don’t panic! As AngularJS 1.x users ourselves we’ve found Angular to be both straightforward and familiar. A little later in this book we’re going to talk specifically about how to convert your AngularJS 1.x apps to Angular.

In the chapters that follow, we won’t be taking a deep dive into each concept, but instead we’re going to give an overview and explain the foundational ideas.

The first big idea is that an Angular application is made up of Components. One way to think of Components is a way to teach the browser new tags. If you have an Angular 1 background, Components are analogous to directives in AngularJS 1.x (it turns out, Angular has directives too, but we’ll talk more about this distinction later on).

However, Angular Components have some significant advantages over AngularJS 1.x directives and we’ll talk about that below. First, let’s start at the top: the Application.

Application

An Angular Application is nothing more than a tree of Components.

At the root of that tree, the top level Component is the application itself. And that’s what the browser will render when “booting” (a.k.a bootstrapping) the app.

One of the great things about Components is that they’re composable. This means that we can build up larger Components from smaller ones. The Application is simply a Component that renders other Components.

Because Components are structured in a parent/child tree, when each Component renders, it recursively renders its children Components.

For example, let’s create a simple inventory management application that is represented by the following page mockup:

Inventory Management App

Given this mockup, to write this application the first thing we want to do is split it into components.

In this example, we could group the page into three high level components

  1. The Navigation Component
  2. The Breadcrumbs Component
  3. The Product List Component

The Navigation Component

This component would render the navigation section. This would allow the user to visit other areas of the application.

Navigation Component

The Breadcrumbs Component

This would render a hierarchical representation of where in the application the user currently is.

Breadcrumbs Component

The Product List Component

The Products List component would be a representation of a collection of products.

Product List Component

Breaking this component down into the next level of smaller components, we could say that the Product List is composed of multiple Product Rows.

Product Row Component

And of course, we could continue one step further, breaking each Product Row into smaller pieces:

  • the Product Image component would be responsible for rendering a product image, given its image name
  • the Product Department component would render the department tree, like Men > Shoes > Running Shoes
  • the Price Display component would render the price. Imagine that our implementation customizes the pricing if the user is logged in to include system-wide tier discounts or include shipping for instance. We could implement all this behavior into this component.

Finally, putting it all together into a tree representation, we end up with the following diagram:

App Tree Diagram

At the top we see Inventory Management App: that’s our application.

Under the application we have the Navigation, the Breadcrumb and the Products List components.

The Products List component has Product Rows, one for each product.

And the Product Row uses three components itself: one for the image, the department, and the price.

Let’s work together to build this application.

You can find the full code listing for this chapter in the downloads under how-angular-works/inventory-app.

source https://www.ng-book.com/2/p/How-Angular-Works/

Angular. Architecture overview

Architecture overview

Angular is a platform and framework for building client applications in HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.

The basic building blocks of an Angular application are NgModules, which provide a compilation context for components. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a root module that enables bootstrapping, and typically has many more feature modules.

  • Components define views, which are sets of screen elements that Angular can choose among and modify according to your program logic and data.
  • Components use services, which provide specific functionality not directly related to views. Service providers can be injected into components as dependencies, making your code modular, reusable, and efficient.

Both components and services are simply classes, with decorators that mark their type and provide metadata that tells Angular how to use them.

  • The metadata for a component class associates it with a template that defines a view. A template combines ordinary HTML with Angular directives and binding markup that allow Angular to modify the HTML before rendering it for display.
  • The metadata for a service class provides the information Angular needs to make it available to components through dependency injection (DI).

An app’s components typically define many views, arranged hierarchically. Angular provides the Router service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.

Modules

Angular NgModules differ from and complement JavaScript (ES2015) modules. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.

Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.

Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the Router NgModule.

Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of lazy-loading—that is, loading modules on demand—to minimize the amount of code that needs to be loaded at startup.

source https://angular.io/guide/architecture

Angularjs – how it works?

When AngularJS starts your application, it parses and processes this new markup from the template using the compiler. The loaded, transformed and rendered DOM is then called the view. The first kind of new markup are the directives. They apply special behavior to attributes or elements in the HTML.

This section briefly touches on all of the important parts of AngularJS using a simple example. For a more in-depth explanation, see the tutorial.

Concept Description
Template HTML with additional markup
Directives extend HTML with custom attributes and elements
Model the data shown to the user in the view and with which the user interacts
Scope context where the model is stored so that controllers, directives and expressions can access it
Expressions access variables and functions from the scope
Compiler parses the template and instantiates directives and expressions
Filter formats the value of an expression for display to the user
View what the user sees (the DOM)
Data Binding sync data between the model and the view
Controller the business logic behind views
Dependency Injection Creates and wires objects and functions
Injector dependency injection container
Module a container for the different parts of an app including controllers, services, filters, directives which configures the Injector
Service reusable business logic independent of views

A first example: Data binding

In the following example we will build a form to calculate the costs of an invoice in different currencies.

Let’s start with input fields for quantity and cost whose values are multiplied to produce the total of the invoice:

<div ng-app ng-init="qty=1;cost=2">
  <b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" ng-model="qty">
  </div>
  <div>
    Costs: <input type="number" min="0" ng-model="cost">
  </div>
  <div>
    <b>Total:</b> {{qty * cost | currency}}
  </div>
</div>

Try out the Live Preview above, and then let’s walk through the example and describe what’s going on.

This looks like normal HTML, with some new markup. In AngularJS, a file like this is called a template. When AngularJS starts your application, it parses and processes this new markup from the template using the compiler. The loaded, transformed and rendered DOM is then called the view.

The first kind of new markup are the directives. They apply special behavior to attributes or elements in the HTML. In the example above we use the ng-app attribute, which is linked to a directive that automatically initializes our application. AngularJS also defines a directive for the input element that adds extra behavior to the element. The ng-model directive stores/updates the value of the input field into/from a variable.

Custom directives to access the DOM: In AngularJS, the only place where an application should access the DOM is within directives. This is important because artifacts that access the DOM are hard to test. If you need to access the DOM directly you should write a custom directive for this. The directives guide explains how to do this.

The second kind of new markup are the double curly braces {{ expression | filter }}: When the compiler encounters this markup, it will replace it with the evaluated value of the markup. An expression in a template is a JavaScript-like code snippet that allows AngularJS to read and write variables. Note that those variables are not global variables. Just like variables in a JavaScript function live in a scope, AngularJS provides a scope for the variables accessible to expressions. The values that are stored in variables on the scope are referred to as the model in the rest of the documentation. Applied to the example above, the markup directs AngularJS to “take the data we got from the input widgets and multiply them together”.

The example above also contains a filter. A filter formats the value of an expression for display to the user. In the example above, the filter currency formats a number into an output that looks like money.

The important thing in the example is that AngularJS provides live bindings: Whenever the input values change, the value of the expressions are automatically recalculated and the DOM is updated with their values. The concept behind this is two-way data binding.

Adding UI logic: Controllers

Let’s add some more logic to the example that allows us to enter and calculate the costs in different currencies and also pay the invoice.

angular.module('invoice1', [])
.controller('InvoiceController', function InvoiceController() {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = ['USD', 'EUR', 'CNY'];
  this.usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };

  this.total = function total(outCurr) {
    return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);
  };
  this.convertCurrency = function convertCurrency(amount, inCurr, outCurr) {
    return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr];
  };
  this.pay = function pay() {
    window.alert('Thanks!');
  };
});

What changed?

First, there is a new JavaScript file that contains a controller. More accurately, the file specifies a constructor function that will be used to create the actual controller instance. The purpose of controllers is to expose variables and functionality to expressions and directives.

Besides the new file that contains the controller code, we also added an ng-controller directive to the HTML. This directive tells AngularJS that the new InvoiceController is responsible for the element with the directive and all of the element’s children. The syntax InvoiceController as invoice tells AngularJS to instantiate the controller and save it in the variable invoice in the current scope.

We also changed all expressions in the page to read and write variables within that controller instance by prefixing them with invoice. . The possible currencies are defined in the controller and added to the template using ng-repeat. As the controller contains a totalfunction we are also able to bind the result of that function to the DOM using {{ invoice.total(...) }}.

Again, this binding is live, i.e. the DOM will be automatically updated whenever the result of the function changes. The button to pay the invoice uses the directive ngClick. This will evaluate the corresponding expression whenever the button is clicked.

In the new JavaScript file we are also creating a module at which we register the controller. We will talk about modules in the next section.

The following graphic shows how everything works together after we introduced the controller:

View-independent business logic: Services

Right now, the InvoiceController contains all logic of our example. When the application grows it is a good practice to move view-independent logic from the controller into a service, so it can be reused by other parts of the application as well. Later on, we could also change that service to load the exchange rates from the web, e.g. by calling the exchangeratesapi.io exchange rate API, without changing the controller.

Let’s refactor our example and move the currency conversion into a service in another file:

angular.module('finance2', [])
.factory('currencyConverter', function() {
  var currencies = ['USD', 'EUR', 'CNY'];
  var usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };
  var convert = function(amount, inCurr, outCurr) {
    return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
  };

  return {
    currencies: currencies,
    convert: convert
  };
});

What changed?

We moved the convertCurrency function and the definition of the existing currencies into the new file finance2.js. But how does the controller get a hold of the now separated function?

This is where Dependency Injection comes into play. Dependency Injection (DI) is a software design pattern that deals with how objects and functions get created and how they get a hold of their dependencies. Everything within AngularJS (directives, filters, controllers, services, …) is created and wired using dependency injection. Within AngularJS, the DI container is called the injector.

To use DI, there needs to be a place where all the things that should work together are registered. In AngularJS, this is the purpose of the modules. When AngularJS starts, it will use the configuration of the module with the name defined by the ng-app directive, including the configuration of all modules that this module depends on.

In the example above: The template contains the directive ng-app="invoice2". This tells AngularJS to use the invoice2module as the main module for the application. The code snippet angular.module('invoice2', ['finance2']) specifies that the invoice2 module depends on the finance2 module. By this, AngularJS uses the InvoiceController as well as the currencyConverter service.

Now that AngularJS knows of all the parts of the application, it needs to create them. In the previous section we saw that controllers are created using a constructor function. For services, there are multiple ways to specify how they are created (see the service guide). In the example above, we are using an anonymous function as the factory function for the currencyConverter service. This function should return the currencyConverter service instance.

Back to the initial question: How does the InvoiceController get a reference to the currencyConverter function? In AngularJS, this is done by simply defining arguments on the constructor function. With this, the injector is able to create the objects in the right order and pass the previously created objects into the factories of the objects that depend on them. In our example, the InvoiceController has an argument named currencyConverter. By this, AngularJS knows about the dependency between the controller and the service and calls the controller with the service instance as argument.

The last thing that changed in the example between the previous section and this section is that we now pass an array to the module.controller function, instead of a plain function. The array first contains the names of the service dependencies that the controller needs. The last entry in the array is the controller constructor function. AngularJS uses this array syntax to define the dependencies so that the DI also works after minifying the code, which will most probably rename the argument name of the controller constructor function to something shorter like a.

Accessing the backend

Let’s finish our example by fetching the exchange rates from the exchangeratesapi.io exchange rate API. The following example shows how this is done with AngularJS:

angular.module('invoice3', ['finance3'])
.controller('InvoiceController', ['currencyConverter', function InvoiceController(currencyConverter) {
this.qty = 1;
this.cost = 2;
this.inCurr = 'EUR';
this.currencies = currencyConverter.currencies;

this.total = function total(outCurr) {
return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
};
this.pay = function pay() {
window
.alert(‘Thanks!’);
};
}]);

Resource: https://docs.angularjs.org/guide/concepts

Who will become the third most expensive company after Apple and Amazon with Angularjs Web Service

The capitalization of the online retailer Amazon briefly exceeded $1 trillion. Microsoft and Google are next who can reach this amount.

On September 4, 2018, Amazon shares exceeded the $2050 mark and the capitalization of the US Internet Magazine for a while became more than $1 trillion. This happened exactly one month after Apple broke the historic market value record and strengthened its price on values ​​above $1 trillion.

Apple has long rivaled Amazon about who will first step over the record sum. Given that now Apple’s capitalization is already $1.1 trillion, and Amazon’s performance fell to $994 billion, it can be safely said that the company from Cupertino defeated the brainchild of Jeff Bezos.

While the Antimonopoly Committee of Europe imposes on Google beggarly $5 billion fines, the American Internet corporation only increases profits and enters into a struggle for the right to become the most expensive company in the world. According to Statista, the top 5 most expensive companies at the beginning of this year were Apple, Amazon, Alphabet (parent company of Google), Microsoft and Facebook.

Who will become the third most expensive company after Apple and Amazon

The indicators remained about the same range, with slight changes. Obviously, leadership remains for Apple, and Amazon is on their heels. The situation is most interesting with the third and fourth place: six months ago Google outperformed Microsoft by almost $16 billion. According to the latest data of Nasdaq, Microsoft’s capitalization is $856 billion, and Google – $837 billion.

According to TechCrunch, in the second quarter of 2018, Alphabet received $32.66 billion in profits, although it did not help Google in the fight against Microsoft.

Facebook certainly became the main loser of the season. Taking into account all the scandals, stock price falls and other swings, the market value of the social network fell to $494 billion. Facebook still remains in the top 5, but now the closest competitors from Google outperform it almost twice. Naturally, the company of Mark Zuckerberg is unlikely to get to $1 trillion in the near future.

Strangely enough, some experts have attributed the achievement of a $1 trillion worth to Tesla by Elon Mask. Of course, unlike others, this company does not receive the main revenue from information technology, but, in any case, the green economy of the future will be based on solutions that Tesla is already implementing. Mask himself, frankly fond of high-profile statements, said that after the acquisition of solar energy company Solar City, the value of the corporation could grow to $1 trillion within one day.

Analyst of the British bank Barclays Ross Sandler predicted that Amazon will somehow become a company with a cost of $1 trillion. The founder and leader of Amazon is the world’s richest man Jeff Bezos. In the international organization Oxfam, which is engaged in reducing poverty, it was estimated that Bezos personally could become the first trillionaire in the world withing the next 25 years.