Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  74] [ 5]  / answers: 1 / hits: 109473  / 7 Years ago, thu, february 2, 2017, 12:00:00

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.


More From » angular

 Answers
6

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


[#59101] Tuesday, January 31, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jacklynr

Total Points: 542
Total Questions: 120
Total Answers: 95

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;