29

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.

Community
  • 1
  • 1
Jaro
  • 1,587
  • 5
  • 20
  • 39

2 Answers2

51

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

  • So is it possible to write it this way : this.taskService.getTask(function(){console.log(tasks);}) // Also i would like to understand why do we use tasks => and not only console.log(tasks) – Jaro Feb 02 '17 at 12:10
  • 2
    yes it is possible to use the `function` notation, but the advantage of using the `arrow` notation (the `=>`) is that it preserves the meaning of `this`, see this [article](https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html) – Tha'er AlAjlouni ثائر العجلوني Feb 02 '17 at 12:15
-4

The main advantage of subscribe comparing to promise then - you can notify changes using observer.next(data) many times and your subscribers will react on each change.

new Observable(observer => observer.next(data));

So if you have several listeners to the same event - all of them will receive change event each time observer generate new data and will call observer.next(). It is very useful when you have data that can be changed frequently and you want single and predictable flow to notify your listeners.

Promise then allow you to wait your async operation once.

VadimB
  • 5,533
  • 2
  • 34
  • 48