What does the .subscribe () function do?

I am coding an API with Angular2 and NodeJS , I am implementing services for my API, which should 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 accepts my response and formats it in an array of values. Here are the task components that use 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 .subscribe() , and I cannot find the relevant information.

+16
source share
2 answers

The .subscribe() function is similar to the Promise.then() , .catch() and .finally() in jQuery , but instead of working with promise it works with Observable s.

This means that it will subscribe to the observable interest (in your case getTasks() ) and will wait until it becomes successful , and then execute the first passed callback function, which in your case:

 tasks => { console.log(tasks); } 

If you want it to start some logic on error (similar to .catch() ) or on completion (similar to .finally() ), you can pass this logic to subscribe as follows:

 observable.subscribe( value => somethingToDoOnlyOnSuccess(value), error => somethingToDoOnlyOnError(error), () => somethingToDoAlways() ); 

More examples and details can be found here.

+23
source

The main advantage of subscribe over the then promise is that you can notify changes repeatedly with observer.next(data) , and your subscribers will respond to every change.

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

So, if you have several listeners for the same event, they will all receive a change event each time the observer generates new data and observer.next() called. This is very useful when you have data that you can change frequently, and you want a single and predictable stream to notify your listeners.

Promise then allows you to wait for the async operation once.

-5
source

Source: https://habr.com/ru/post/1014644/


All Articles