Monday, 28 August 2017

REST API

INTRODUCTION

Application program interface(API) is a set of routines, protocols, and tools for building software applications. It specifies how software components should interact. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the block together.

WHAT IS REST API?

REST is any interface between systems using HTTP to obtain data and generate operations on those data in all possible formats, such as XML and JSON. Developers do not need to need to install libraries or additional software in order to take advantage of REST API design.

HISTORY OF REST API

In 1999, most developers had to deal with SOAP—Simple Object Access Protocol— to integrate APIs. And the “simple” part of that acronym is not to be taken literally. To make a call, they had to hand-write an XML document with an RPC call in the body. From there, they had to specify the endpoint and POST their SOAP envelope to that specified endpoint.
SOAP was notorious for being complex to build, complex to use, and near-impossible to debug. And the alternative, CORBA, was even worse. The problem was that there was no standard for how APIs should be designed and used. Back then, APIs were not designed to be accessible, they were only designed to be flexible.
But a small group of expert developers recognized the true potential of web APIs. Thanks to this small group, led by Roy Fielding, REST was coined and the API landscape changed forever.
In 2000, Roy Fielding and his colleagues had one objective: create a standard so that any server could talk to any other server in the world. Roy Fielding gave the disorganized internet world the gift of a common language through which their software could communicate.

RESTFUL WEBSERVICES FOR ANGULAR 2

The Angular HTTP client communicates with the server using a familiar HTTP request/response protocol. The Http client is one of a family of services in the Angular HTTP library. When importing from the @angular/HTTP module, SystemJS knows how to load services from the Angular HTTP library because the systemjs.config.js file maps to that module name. The HttpModule is necessary for making HTTP calls.

Observable

Think of an Observable as a stream of events published by some source. To listen for events in this stream, subscribe to the Observable. These subscriptions specify the actions to take when the web request produces a success event or a fail event (with the error in the payload).
  • The observable’s map callback moves to the success parameter and its catch callback to the fail parameter in this pattern.
  • The errorHandler forwards an error message as a failed promise instead of a failed observable.

RxJS library

  • RxJS (“Reactive Extensions”) is a 3rd party library, endorsed by Angular, that implements the asynchronous observable pattern.
  • RxJS npm package loaded via system.js because observables are used widely in Angular applications.
  • The app needs it when working with the HTTP client. Additionally, you must take a critical extra step to make RxJS observables usable.
  • The RxJS library is large. Size matters when building a production application and deploying it to mobile devices. You should include only necessary features.
  • Accordingly, Angular exposes a stripped down version of Observable in the rxjs/Observable module that lacks most of the operators such as the map method.
  • You could add every RxJS operator with a single import statement. While that is the easiest thing to do, you’d pay a penalty in extended launch time and application size because the full library is so big.
  • Since this app only uses a few operators, it’s better to import each Observable operator and static class method, one-by-one, for a custom Observable implementation tuned precisely to the app’s requirements. Put the import statements in one app/rxjs-operators.ts file.
Below is the HTTP signature as is in Angular 2 source:
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
request(url: string | Request, options?: RequestOptionsArgs): Observable;
/**
* Performs a request with `get` http method.
*/
get(url: string, options?: RequestOptionsArgs): Observable;
/**
* Performs a request with `post` http method.
*/
post(url: string, body: any, options?: RequestOptionsArgs): Observable;
/**
* Performs a request with `put` http method.
*/
put(url: string, body: any, options?: RequestOptionsArgs): Observable;
/**
* Performs a request with `delete` http method.
*/
delete(url: string, options?: RequestOptionsArgs): Observable;
/**
* Performs a request with `patch` http method.
*/
patch(url: string, body: any, options?: RequestOptionsArgs): Observable;
/**
* Performs a request with `head` http method.
*/
head(url: string, options?: RequestOptionsArgs): Observable;
Each method takes in a url and a payload as the case may be and returns a generic observable response type.
The service class has the following structure:
/* * * ./app/comments/services/comment.service.ts * * */
// Imports
import { Injectable } from ‘@angular/core’;
import { Http, Response, Headers, RequestOptions } from ‘@angular/http’;
import { Comment } from ‘../model/comment’;
import {Observable} from ‘rxjs/Rx’;
// Import RxJs required methods
import ‘rxjs/add/operator/map’;
import ‘rxjs/add/operator/catch’;
@Injectable()
export class CommentService {
// Resolve HTTP using the constructor
constructor (private http: Http) {}
// private instance variable to hold base url
private commentsUrl = ‘http://localhost:3000/api/comments’;
}
We are importing the required libraries for our service to behave as expected. The observable about has also been imported and ready for use. The map and catch observable operators which will help us manipulate data and handle errors respectively has also been imported. Then we inject HTTP in the constructor and keep a reference to the base url of our API.
// Fetch all existing comments
getComments() : Observable<Comment[]> {
// …using get request
return this.http.get(this.commentsUrl)
// …and calling .json() on the response to return data
.map((res:Response) => res.json())
//…errors if any
.catch((error:any) => Observable.throw(error.json().error || ‘Server error’));
}
Using the http instance we already have on the class, we call it’s get method passing in the base url because that is the endpoint where we can find a list of comments.
We are maintaining strictness by ensuring that the service instance methods always return an observable of type Comment:
/* * * ./app/comments/model/comment.ts * * */
export class Comment {
constructor(
public id: Date,
public author: string,
public text:string
){}
}
With the map operator, we call the .json method on the response because the actual response is not a collection of data but a JSON string.
It is always advisable to handle errors so we can use the catch operator to return another subscribable observable but this time a failed one.
The rest of the code has the above structure but different HTTP methods and arguments:
// Add a new comment
addComment (body: Object): Observable<Comment[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ ‘Content-Type’: ‘application/json’ }); // … Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this.commentsUrl, body, options) // …using post request
.map((res:Response) => res.json()) // …and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || ‘Server error’)); //…errors if any
}
// Update a comment
updateComment (body: Object): Observable<Comment[]> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ ‘Content-Type’: ‘application/json’ }); // … Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.put(`${this.commentsUrl}/${body[‘id’]}`, body, options) // …using put request
.map((res:Response) => res.json()) // …and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || ‘Server error’)); //…errors if any
}
// Delete a comment
removeComment (id:string): Observable<Comment[]> {
return this.http.delete(`${this.commentsUrl}/${id}`) // …using put request
.map((res:Response) => res.json()) // …and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || ‘Server error’)); //…errors if any
}
The above makes a postput and delete request, converts response to JSON and catches error if any.
Observables are not as mouthful as it seemed in the beginning. What’s is just left to do is subscribe to the observable and bind the data as they are emitted to the views.

Monday, 21 August 2017

Components in Angular2

INTRODUCTION:

Components are the core building block of Angular 2 applications. A good technical definition would be “components in Angular 2 are a framework construct that owns a single node of HTML and dictates what children are written to that node, and handle all interaction with those children”.

There is one root component called app.component. Then there are components and subcomponents. The following example will make it more clear:
Screenshot 2017-07-03 17.40.33
In this example app.component is the root component, header ,body and footer are its component and signup-login are subcomponents of body.

How to create a component:

Create a new file src/app folder with the name
<component_name>.component.ts
Eg – my-header.component.ts
In the file write the following:
Screenshot 2017-07-03 17.40.39
This is the basic structure of a component.
If you working with Angular CLI then write the following command in command prompt and your component will be created with the structure shown above:
Screenshot 2017-07-03 17.40.43

Explaining the structure of the component:

Component represents a reusable piece of UI that is usually depicted by a custom html element.It consists of the following –
  • Selector- the aforementioned html element which will match the element tag that identifies this
  • Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.
  • Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript.
  • Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.
Components are very helpful as they make our code more understandable to other person by dividing the whole structure into various parts.And we can reuse these components in different applications as well.
WHY IT CAME INTO EXISTENCE WHEN CONTROLLERS WERE ALREADY THERE:
A lot of changes are there in Angular 1 and Angular 2.And one stand-out feature change is the introduction of components. Angular 2 is entirely component based. Components and directives have replaced the controllers and $scope of Angular 1. Components are directives with a template.
Difference-betwee-Angular-1-vs-angular2
In Angular 1 we’d attach controllers to various parts of the page with our custom logic. Scopes would be attached or flow through, based on how our custom directives encapsulated themselves.In this model it wasn’t like any hierarchical structure. We’d just “attach” behaviors to various parts of our page and then have to deal with the complicated meta-structure created by our directives, controllers, and scopes.
To add logic to the page, we’d have to decide between building a controller or a custom directive.
Angular 2 drops all of this for a much cleaner, more object-oriented Component model.

Example of Controller in Angular 1 and Components in Angular 2 :

Angular 1 Controller:
Screenshot 2017-07-03 17.40.53
Angular 2 Components:
Screenshot 2017-07-03 17.40.59
This was all about Components.Try making a new component and learn more about it.
Keep learning.

Monday, 14 August 2017

Faster than expected - HyperLoop


hyperloopconcept.jpg

         



Whenever something comes into the market there is this one thing that let the occurrence and that is nothing but “Requirement or need”. Hyperloop is such one development in the industry of science and technology which dealt with the requirements.

Where it was started?

In year 2012, the renowned innovator Elon Musk released its first version which tells that some people will be travelling in capsules running on air bearings driven by motors and air compressors.
Like a spark, this ignites many minds and in year 2013, a paper on this concept was published which creates an idea of a hyperloop system that would propel passengers along the 350-mile (560 km) route at an average speed of around 600 mph (970 km/h), with a top speed of 760 mph (1,200 km/h), allowing for a travel time of 35 minutes, which is considerably faster than current rail or air travel times and after so many efforts from commercial companies and dozens of student teams,  on January 29, 2017, approximately one year after winning phase one of the Hyperloop pod competition, the MIT Hyperloop pod demonstrated the first ever low-pressure Hyperloop run in the world [credits : Wikipedia].
Oh, didn’t i tell you Why Hyperloop ?
Because it is fast, cheaper(after some initial phase, probably), safer, efficient, quiet. In short, it is WOW.
You will come to know why i am saying this, bear with me :D


So, what is this buzzword?




Because no one else can tell you better than Hyperloop One


Who is working on it?


Hyperloop one and Hyperloop transportation technologies are the two main leaders in this field for now, also some support is backed up by the addition of Arrivo chaired by ex-Hyperloop One CTO and ex-SpaceX engineer Brogan BamBrogan.
It doesn't ends here, Elon Musk runs a Hyperloop Challenge, where he welcomes students to his Hyperloop test lab in his SpaceX facility in Las Vegas.  .
This global challenge invites people from around the world to make a comprehensive commercial, or transport or can be economic related for their cities, regions or even countries which can be considered to host the first hyperloop networks. It’s not an engineering competition, they say : “we bring technology, you tell us how it should be used in your location”.
I hope you must be thinking when can i have one ride in this, but the answer is little disappointing, “we are really not sure” , But don’t be sad Musk track record of getting things done gives a ray of light to the Hyperloop project.
Hyperloop One lists a projected date of 2021 on its website for having “three production systems”, although what that means in terms of working transport is unclear. Hyperloop One chief executive Rob Lloyd has claimed that, following an agreement with Dubai, “from a technological point of view, we could have a Hyperloop One system built in the United Arab Emirates (UAE) in the next five years”.  So let's hope for the best and maybe some day a ride in hyper wouldn't be just a dream.
Source : techradar.com

--- Swapnil kumar & Sunil kumar