Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the .subscribe() function do?

Tags:

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.

like image 724
Aria Groult Avatar asked Feb 02 '17 11:02

Aria Groult


People also ask

What will subscribe do in Angular?

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.

What is a subscription in JavaScript?

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".

What does it mean to subscribe to an Observable?

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.

What is subscribe in jQuery?

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.


1 Answers

The .subscribe() function is similar to the Promise.then(), .catch() and .finally() methods in jQuery, but instead of dealing with promises it deals with Observables.

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

like image 191
Tha'er M. Al-Ajlouni Avatar answered Oct 06 '22 23:10

Tha'er M. Al-Ajlouni