I am coding an API with Angular2
and NodeJS
, I am implementing services for my ِAPI that is supposed to get a list of tasks and display it. Here is the task service:
import {Injectable} from '@angular/core'; import {Http, Headers} from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class TaskService{ constructor(private http:Http){ console.log('Task Service Initialized...'); } getTasks(){ return this.http.get('http://localhost:3000/api/tasks') .map(res => res.json()); } }
For my getTask
function (correct me if I am wrong) the .map()
function takes my response and formats it in an array of values. Here is now, the task components that uses the task service:
import { Component } from '@angular/core'; import {TaskService} from '../../services/task.service'; @Component({ moduleId: module.id, selector: 'tasks', templateUrl: 'tasks.component.html', }) export class TasksComponent { constructor(private taskService:TaskService){ this.taskService.getTasks() .subscribe(tasks =>{ console.log(tasks); }) } }
I would like to understand what this .subscribe()
function does and I can't find any relevant information.
Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.
A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe , that takes no argument and just disposes the resource held by the subscription. In previous versions of RxJS, Subscription was called "Disposable".
Subscribing to an Observable is like calling a function, providing callbacks where the data will be delivered to. This is drastically different to event handler APIs like addEventListener / removeEventListener . With observable. subscribe , the given Observer is not registered as a listener in the Observable.
The Publish Subscribe or pub/sub pattern is used to logically decouple object(s) that generate an event, and object(s) that act on it. It is a useful pattern for object oriented development in general and especially useful when developing asynchronous Javascript applications.
The .subscribe()
function is similar to the Promise.then()
, .catch()
and .finally()
methods in jQuery
, but instead of dealing with promise
s it deals with Observable
s.
That means it will subscribe itself to the observable
of interest (which is getTasks()
in your case) and wait until it is successful
and then execute the first passed callback function which in your case is:
tasks => { console.log(tasks); }
If you want it to run some logic on error (similar to .catch()
) or on complete (similar to.finally()
) you can pass that logic to the subscribe
as following:
observable.subscribe( value => somethingToDoOnlyOnSuccess(value), error => somethingToDoOnlyOnError(error), () => somethingToDoAlways() );
More examples and details can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With