Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

Wednesday, April 1, 2020

Difference between TypeScript and JavaScript


JavaScript (JS) and TypeScript (TS) are two widely used programming languages that are popular for their feature-rich benefits. JavaScript was first introduced as a client-side language for developers. Later on, it was found that JavaScript could also be used for server-side programming purposes. Over time, JavaScript codes became heavy and complex and failed to fulfill the purpose of general object-oriented programming languages. There were gaps that emerged in terms of JavaScript being used as a server-side technology for enterprise-level development. Thereafter, TypeScript was developed to help developers take care of these shortfalls.
We will begin with a comparison chart depicting the difference between TypeScript and JavaScript. We will discuss why developers use JavaScript and TypeScript, the features of JavaScript and TypeScript, etc.


Typescript vs. JavaScript

Comparison Chart: Primary Differences Between JavaScript and TypeScript

JavaScript
TypeScript
It is a scripting language
It is an OOP (object-oriented programming) language
Static typing feature is not available
Static typing feature is present; it is a light-weight
No support for modules is present in JavaScript
TypeScript supports modules in the development process
Interface is not present
TypeScript contains an interface that makes development more convenient and user-friendly
The optional parameter function is not supported by JavaScript
TypeScript provides support for optional parameter functions
Specifically used for client-side operations
Used for both client and server-side operations
.js
.ts, .tsx
In JavaScript, all the codes are written within the <> script tags. This tells the browser to start interpreting the text that’s written as code within the tags during run time.
The codes written in TypeScript comprise of modules, functions, variables, comments, statements and expressions.
·   It boasts of a huge active community comprising of developers.
·      JavaScript supports native browsers and cuts out on one extra step of compiling as is required in TypeScript.
·       More flexibility.

·       Static Typing
·   More preferable for complex, large-sized projects
·      A better option for collaboration especially when there are many   developers working on large projects.
·   Type safety presents sound features for detecting errors right at the coding time. This leads to efficient coding, higher productivity and easy debugging.

What is JavaScript?
JavaScript or JS is a development language that is used for updating and changing HTML and CSS codes. This popular dynamic programming language is mainly utilized for web development and for enhancing HTML pages. JavaScript can calculate, assess, manipulate, validate and test data. JavaScript is generally used as client-side scripting and coding language. When anyone requests an HTML page that has JavaScript code in its, the script goes to the browser; the browser is responsible for taking the requisite actions. JS is the brainchild of Brendan Eich. It first made its appearance in the year 1995 when it was used by the Netscape Navigator browser attributed to Netscape.

Features of Javascript
  1. JavaScript is an object-based programming language that gives users a lot of control on the browser.
  2. It is light-weighted.
  3. JavaScript is case sensitive.

What is Typescript?       
Typescript is a popular open-source development language. It can be defined as the next- level of JavaScript for application-scale development purposes. This programming language is an object oriented, strongly typed, compiled language. TypeScript serves the dual purpose of a set of tools and a language. Invented by Anders Hejlsberg, TypeScript is licensed by Apache 2. Also referred to as a superset of JavaScript, TypeScript is designed and developed for taking care of complicated projects. It comes packaged with extra loaded features in addition to those present in Java Script. All TypeScript codes are changed into JavaScript equivalents for their execution.

Features of TypeScript
  1. TypeScript provides support for JavaScript libraries and can access JavaScript frameworks and tools as well as other libraries easily.
  2. JavaScript with valid .js extension can be converted to TypeScript by changing the extension from .js to .ts; they can be compiled with other TypeScript files.
  3. TypeScript is portable and can run on all devices, browsers, devices and operating systems.
Advantages of using TypeScript over JavaScript
Why typescript? There are certain advantages of using TypeScript in comparison to JavaScript:
1. The compilation errors are pointed out by TypeScript in the course of development only. This is not possible in the case of JavaScript. Because of this important feature of typescript, there are few chances of errors occurring during run time. JavaScript, being an interpreter-based language, fails to provide this feature.
2. TypeScript supports static typing; its features are supportive of strongly-typed codes that allow for the checking of type correctness during the time of compilation. Here, TypeScript scores over JavaScript as this feature is not found in the latter.
3. TypeScript has some additional features, for example, ES6 features, of JavaScript. The TypeScript compiler is capable of compiling the .ts files in line with the ES6 features as well as those belonging to ES3, ES4 and ES5 features. However, it is important for developers to check if these features are supported by their target browsers or not.
4. The main advantage that Typescript has over JavaScript is that it is designed for developing complex and large programs. It is a superset of JavaScript. TypeScript codes can be trans compiled to JavaScript.
5. Typescript is supportive of definition file that can store file type information comprising of existing JavaScript libraries, such as the C++ header files. In turn, this feature helps other programs utilize the values that are defined in those specific files. This is not possible with JavaScript.

Conclusion
The choice of TypeScript or JavaScript would depend on the complexity and size of the project for which they are used. Knowledge of the primary differences between typescript and JavaScript helps in understanding the application of these two languages. In case you have any further queries with regards to what is typescript, what is JavaScript, benefits in the relation of JavaScript to typescript, or the differences between typescript vs JavaScript, then write to us. We will be happy to provide the most suitable answers to your queries at the earliest.


Introduction to Angular

"Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection, end to end tooling, and integrated best practices to solve development challenges. Angular empowers developers to build applications that live on the web, mobile, or the desktop". 

Single Page Applications

Basically, when people talk about Angular, they talk about it as a JavaScript framework. It is used to build so-called Single Page Applications (SPA). These SPA's typically (but not only) use the browsers JavaScript environment to emulate the behavior of normal websites.

Because they don't rely on a server at all, they can do things, that we would expect from native applications. They have the ability to manage their state completely client-side, enabling a richer and much more fluent user experience.
Furthermore. server-round-trips can be avoided to a bare minimum, resulting in an overall more responsive application.

Thanks to technologies like Service Workers and Progressive Web Apps, these applications can become almost indistinguishable from native applications, especially on mobile (Android) devices.

The Framework

The Angular framework enables us to write these single page applications with ease. It comes with features like data-binding, change-detection, forms, routing & navigation and an HTTP-implementation right out of the box.
Angular was originally intended to be used with the programming languages JavaScript, TypeScript and Dart. And although it is still possible to use it with all of these languages, the by far most popular language of choice became TypeScript.
I would highly recommend using TypeScript, as the other versions are not only lacking documentation and community, but updates are also released much later (months not days) than for the TypeScript version.

The Platform

Over time, the angular developers have developed a great ecosystem around the framework.
Tools like the Angular-Cli, Angular Universal and Angular Material got added to the project. These tools added great features like fast project generation, server-side rendering, and stunning UI components, that are not coupled with the core-framework itself, but completely optional.
That is why angular is referred to as a platform. It provides all the tools, that you need, to develop great angular applications, without relying too much on third-party libraries. Because of this opinionated approach, most developers are using these tools, resulting in a great documentation, community help, and blog posts.

Is it called AngularJS or Angular ?

Maybe one of the greatest downsides of angular, to me, is the version and naming chaos that emerged after the Angular 2 release. Google decided to row back from the terms Angular 2, Angular 4, Angular 5, but to refer to them as just "Angular".
Don't get me wrong, having the universal "Angular" name for all version 2+ was the right decision, in my opinion. But this more general term makes searching (Google etc.) and finding the right information really hard.

Angular Features

A list of the most important features and benefits of Angular:

1.     Angular supports multiple platforms: Angular is a cross-platform language. It supports multiple platforms. You can build different types of apps by using Angular.

·      Desktop applications: Angular facilitates you to create desktop installed apps on different types of operating systems i.e. Windows, Mac or Linux by using the same Angular methods which we use for creating web and native apps.
·       Native applications: You can build native apps by using Angular with strategies from Cordova, Ionic, or NativeScript.
·    Progressive web applications: Progressive web applications are the most common apps which are built with Angular. Angular provides modern web platform capabilities to deliver high performance, offline, and zero-step installation apps.

2.     High Speed, Ultimate Performance: Angular is amazingly fast and provides a great performance due to the following reasons:

·       Universal support: Angular can be used as a front-end web development tool for the programming languages like Node.js, .Net, PHP, Java Struts and Spring and other servers for near-instant rendering in just HTML and CSS. It also optimizes the website for better SEO.
·      Code splitting: Angular apps are fast and loads quickly with the new Component Router, which delivers automatic code-splitting so users only load code required to render the view they request.
·    Code generation: Angular makes your templates in highly optimized code for today?s JavaScript virtual machines which gives the benefits of hand-written code.

3.     Productivity: Angular provides a better productivity due to its simple and powerful template syntax, command-line tools and popular editors and IDEs.

·      Powerful templates: Angular provides simple and powerful template syntax to create UI view quickly.
·     IDEs: Angular provides intelligent code completion, instant errors, and other feedback in popular editors and IDEs.
·      Angular CLI: Angular CLI provides command line tools start building fast, add components and tests, and then instantly deploy.

4.     Full Stack Development: Angular is a complete framework of JavaScript. It provides Testing, animation, and Accessibility. It provides full-stack development along with Node.js, Express.js, and MongoDB.

·      Testing: Angular provides Karma and Jasmine for unit testing. B y using it, you can check your broken things every time you save. Karma is a JavaScript test runner tool created by Angular team. Jasmine is the testing framework form unit testing in Angular apps, and Karma provides helpful tools that make it easier to us to call our Jasmine tests whilst we are writing code.
·     Animation Support: Angular facilitates you to create high-performance, complex choreographies and animation timelines with very little code through Angular's intuitive API.
·   Accessibility: In Angular, you can create accessible applications with ARIA-enabled components, developer guides, and built-in test infrastructure.

Wednesday, March 25, 2020

Angular Service


Services in Angular are a great deal to share information among classes that do not know each other.  When we are developing the Angular app, we will most likely run into an outline in which we need to use the exact same code across multiple angular components. In that case, the Services will help us to get rid of that problem. We can share the services code among various angular components.
With Angular’s dependency injectionyou can inject the services around your app. 
Why we use Angular Service
There are many reasons why you would want to create and use the services in your Angular applications. One of the most common is the data service. The class that will handle getting and setting data from your datastore.
The data service that gets injected into each of those components allows you not to have to recreate the same datastore connection code in each component. Another common use of service is for some business logic.
The Angular framework has classes that are necessarily service classes. Things like HttpFormBuilder, and more, contain logic for doing specific things that are non-component specific. And again, through the dependency injection engine, you can get these services sent into your class constructors and use them.
Services in Angular provide an architectural way to encapsulate business logic in a reusable fashion, allowing you to keep that logic out of your components, directives, and pipe classes. This is not only beneficial for modularity, and single responsibility type of simplicity tier code, but it also makes the code more testable. 
If you employ a unit testing strategy, it becomes straightforward to mock the services that get used in a component. Thus your unit test can focus purely on confirming the behavior of the component and not its dependencies. 
Same goes for your services that get other services provided to them. So services, while not an enforced construct, are a fundamental building block to an Angular application.
In this case, Components use to display and present the data. Services use to fetch a data from an API. Let’s start our Angular Service Example. 
Angular 5 Service Example-1
Create a Service class: To create an angular service class, at the console, type the following command in your root of the folder.
ng g service services/myservice –flat true
create src\app\services\myservice.service.spec.ts
create src\app\services\myservice.service.ts
WARNING Service is generated but not provided, it must be provided to be used
It will create the following files.
  1. myservice.service.ts
  2. myservice.service.spec.ts

myservice.service.ts

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class MyServiceService {
  
  constructor() {}
}
Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class.
Before creating a new service, we need to include the service created in the main parent app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyserviceService } from './services/service1.service';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CardserviceComponent,
    Card1Component,
    Card2Component,
    ServiceComponentComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [Service1ServiceMyserviceService],
  bootstrap: [AppComponent]
})
export class AppModule {}

We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function.
In the service class, we will create a function that will display today’s date.  
Let us now see how the function looks in the service and how to use it in components.

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class MyserviceService {
  serviceproperty = 'Service Created and Injected';
  constructor() {}

  showTodayDate() {
    let ndate = new Date();
    return ndate;
  }
}

In the above service file, we have created a function showTodayDate. Now we will return the new Date () created.
Let us now see how to use the service in the new component created.

Service-Component.component.ts

import { ComponentOnInit } from '@angular/core';
import { MyserviceService } from '../services/myservice.service';

@Component({
  selector: 'app-service-component',
  templateUrl: './service-component.component.html',
  styleUrls: ['./service-component.component.css']
})
export class ServiceComponentComponent implements OnInit {
  todaydate;
  msg;
  constructor(private myserviceMyserviceService) {}

  ngOnInit() {
    this.todaydate = this.myservice.showTodayDate();
    this.msg = this.myservice.serviceproperty;
  }
}

The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component .ts file.We will display the date in the Service-Component.component.html file as shown below –
<h2>
  {{ msg }}
</h2>
<h2>Today's Date : {{ todaydate }}</h2>

The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below –
Output (Service Example-1):


Global service vs. Local Service Injection in Angular 

( Dependency Injection )

To inject the service, you have the following two options.

1)     Inject as ‘global service.’

To inject as a global service, inject a service into the root module.
You need to register the module inside the app.module.ts file like we have done earlier in this post.
import { MyServiceService } from './services/Myservice.service'; 

@NgModule({ providers: [MyServiceService], })

2)     Inject as ‘local service’

To inject as local service, inject the service into component directly.
See the following code inside the Service-Component.component.ts file.

import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../services/Myservice.service'; 
 
@Component({
  selector: 'app-service-component',
  templateUrl: './ service-component.component.html',
  styleUrls: ['./ service-component.component.css'],
  providers: [MyServiceService]
})
export class ServiceComponentComponent implements OnInit{
  todaydate;
  msg;
 
  constructor(private myservice: MyserviceService){  }
  ngOnInit(){
     this.todaydate = this.myservice.showTodayDate();
     this.msg = this.myservice.serviceproperty;   
  }
}

So, we can register the service in Angular, either locally or globally.
If you are using services on more than one component, then you should define one global, and otherwise, local works just fine. It depends on the size of the project.