Javascript .subscribe() 函数有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42000883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:49:06  来源:igfitidea点击:

What does the .subscribe() function do?

javascriptangularrxjsobservable

提问by Aria Groult

I am coding an API with Angular2and 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:

我正在使用Angular2和编写 API NodeJS,我正在为我的 ?API 实现服务,该服务应该获取任务列表并显示它。这是任务服务:

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 getTaskfunction (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:

对于我的getTask函数(如果我错了,请纠正我)该.map()函数接受我的响应并将其格式化为值数组。现在是使用任务服务的任务组件:

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.

我想了解此.subscribe()功能的作用,但找不到任何相关信息。

回答by Tha'er M. Al-Ajlouni

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.

.subscribe()函数类似于 中的Promise.then(),.catch().finally()方法jQuery,但promise它处理的是Observables ,而不是处理s。

That means it will subscribe itself to the observableof interest (which is getTasks()in your case) and wait until it is successfuland then execute the first passed callback function which in your case is:

这意味着它将自己订阅observable感兴趣的(getTasks()在您的情况下)并等待它successful,然后执行第一个传递的回调函数,在您的情况下是:

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 subscribeas following:

如果您希望它在错误(类似于.catch())或完成(类似于.finally())时运行某些逻辑,您可以将该逻辑传递给subscribe如下:

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

More examples and details can be found here

可以在此处找到更多示例和详细信息

回答by VadimB

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

subscribe与 promise 相比的主要优势then- 您可以observer.next(data)多次通知更改,并且您的订阅者将对每次更改做出反应。

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.

因此,如果您对同一事件有多个侦听器 - 每次观察者生成新数据并调用observer.next(). 当您拥有可以频繁更改的数据并且您希望单一且可预测的流程通知您的听众时,它非常有用。

Promise thenallow you to wait your async operation once.

Promisethen允许您等待一次异步操作。