如何在Angular 6中使用参数创建可观察的对象? [英] How create observable with parameters in Angular 6?

查看:64
本文介绍了如何在Angular 6中使用参数创建可观察的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以在Angular 6中传递一些参数的观测站. 以下是在Angular网站中创建可观察的示例代码 https://angular.io/guide/observables ,但没有说明如何传递任何参数.

I want to create an observale which can pass some parameters in Angular 6. Below is the sample code for creating observable in Angular site https://angular.io/guide/observables, but it doesn't explain how to pass any parameters.

// Create an Observable that will start listening to geolocation updates
// when a consumer subscribes.
const locations = new Observable((observer) => {
  // Get the next and error callbacks. These will be passed in when
  // the consumer subscribes.
  const {next, error} = observer;
  let watchId;

  // Simple geolocation API check provides values to publish
  if ('geolocation' in navigator) {
    watchId = navigator.geolocation.watchPosition(next, error);
  } else {
    error('Geolocation not available');
  }

  // When the consumer unsubscribes, clean up data ready for next subscription.
  return {unsubscribe() { navigator.geolocation.clearWatch(watchId); }};
});

// Call subscribe() to start listening for updates.
const locationsSubscription = locations.subscribe({
  next(position) { console.log('Current Position: ', position); },
  error(msg) { console.log('Error Getting Location: ', msg); }
});

// Stop listening for location after 10 seconds
setTimeout(() => { locationsSubscription.unsubscribe(); }, 10000);

我想要的是订阅时将一些参数传递给observable,我想observable的定义可能像这样:

What I want is pass some parameters to observable when I subscribe it, I guess the definition of observable may be looks like:

const myobservable(a, b) = new Observable((observer) => {
  ...
})

您能告诉我该怎么做吗?

Could you please tell how can I do that?

推荐答案

您无法将参数传递给subscribe,subscribe是一个回调函数,当以可观察的顺序发出每个值时将执行该回调函数.

You couldn't pass a parameter in to the subscribe , subscribe is a call back function which will execute when emit each value in a observable sequence.

订阅时,您可以将值作为参数传递给未订阅的函数,并对该参数进行操作

When you subscribe , you can pass the value as a parameter in to the function not subscribe and do something with the parameter

SomeObservableFunction(10).subscribe(function(x){

});

为了了解可观察的工作原理,请查看下面的示例代码片段

In order to understand how observable works look at the below sample code snippet

 var observable = Observable.create(function(observer) {
      var sum = 0;
      for (var i = 1; i <= 4; i++) {
        if (i <= 3) {
          sum = sum + i;
           observer.next(i);  //You can emit each item from the observable also
        }
        if (i === 4) {
          setTimeout(
            i => {
              observer.next(sum);
              observer.complete();
            },
            5000,
            i
          );
        }
      }
    });

在此示例代码中,我正在运行一个for循环,并使用observer.next(value)发出每个值,当i的值变为4时,您将看到发出3个数字的总和并通过退出所有可观察到的序列简单调用observable.complete();

In this sample code, I am running a for loop and emit each value by using observer.next(value) , when the value of i become 4 you can see emiting the sum of 3 numbers and exiting the all observable sequence by simple calling observable.complete();

Observables是惰性的,意味着,以上代码从不执行 除非您订阅它.

Observables are lazy which means , the above code never executes unless you are subcribing it.

让我们订阅以获取每个值.我删除了lamda表达式以更清楚地理解

Let's subscribe to get each value. I am removing the lamda expression to understand more clearly

 observable.subscribe({
      next: function(x) {

        console.log("got value " + x);
      },
      error: err => console.error("something wrong occurred: " + err),
      complete: function() {
         //when I become 4 it will complete
        console.log("completed");
      }
    });

在next的回调函数中,您将获得我们从可观察对象发出的所有值,包括sum作为最终值,然后它将执行完整的回调函数.

In the callback function of next , you will get all the values we emitted from the observable including sum as final value and then it will execute the complete callback function.

您也可以像下面的语法一样简单地接收每个值,类似于下一个回调

You can simply receive each value like the below syntax also , which is similar to next callback

  observable.subscribe(function(x) {
      //here you will get all the value including sum
      console.log(x);
    });

让我通过简单地注释一行代码来告诉您使用相同样本的另一种情况.我并没有发出每个值,而是只想从可观察且完整的位置发出和.

Let me tell you one more scenario with the same sample by simply commenting one line of code. I am not emitting each value instead I want to emit the sum only from the observable and complete.

 var observable = Observable.create(function(observer) {
      var sum = 0;
      for (var i = 1; i <= 4; i++) {
        if (i <= 3) {
          sum = sum + i;
            //commented the code
        }
        if (i === 4) {
          setTimeout(
            i => {
              observer.next(sum);
              observer.complete();
            },
            5000,
            i
          );
        }
      }
    });

现在,当您订阅时,您将只有一个值,即sum

Now when you subscribe , you will have only one value , that is sum

 observable.subscribe(function(x) {
      //here you will get the sum
      console.log(x);
    });

现在返回您的问题,要传递参数,您可以将整个observable包装到一个返回observable的函数中.例如

Now returning to your question , to pass parameter you can wrap up the entire observable in to a function which return an observable. For example

SomeObservableFunction(someparam){
var observable = Observable.create(function(observer) {
       //I am not writing the same code block here 
    });
return observable;
}

这篇关于如何在Angular 6中使用参数创建可观察的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆