【问题标题】:How create observable with parameters in Angular 6?如何在 Angular 6 中使用参数创建 observable?
【发布时间】:2019-02-24 06:19:35
【问题描述】:

我想创建一个可以在 Angular 6 中传递一些参数的 observale。 下面是在 Angular 站点 https://angular.io/guide/observables 中创建 observable 的示例代码,但它没有解释如何传递任何参数。

// 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 的定义可能是这样的:

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

您能告诉我该怎么做吗?

【问题讨论】:

    标签: angular observable


    【解决方案1】:

    您无法将参数传递给 subscribe , subscribe 是一个回调函数,它将在发出可观察序列中的每个值时执行。

    当你订阅时,你可以将值作为参数传递给不订阅的函数,并对参数做一些事情

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

    为了了解 observable 的工作原理,请查看以下示例代码 sn-p

     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();

    Observables 是惰性的,这意味着上面的代码永远不会执行 除非你订阅它。

    让我们订阅以获取每个值。我正在删除 lamda 表达式以便更清楚地理解

     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 的回调函数中,您将获取我们从 observable 发出的所有值,包括 sum 作为最终值,然后它将执行完整的回调函数。

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

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

    让我通过简单地注释一行代码来告诉您使用相同示例的另一个场景。我没有发出每个值,而是只想从可观察的和完整的中发出总和。

     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

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

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

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

    【讨论】:

    • 你应该先给出一个简短的答案,然后再给出解释。谢谢你的回答。
    • @shyam_ 你说得对,我更新了答案。感谢您的建议
    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 2018-10-20
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2021-05-02
    • 2018-12-28
    • 2016-05-26
    相关资源
    最近更新 更多