简体   繁体   English

Angular Observables 返回匿名函数

[英]Angular Observables return anonymous function

I have this method that I copied from a websocket tutorial but I don't understand the meaning of the "return () => { ... }" inside the observable ?我有这个方法是从 websocket 教程中复制的,但我不明白 observable 中“return () => { ... }”的含义? Can someone explain me what is the purpose of that ?有人可以解释我这样做的目的是什么吗?

  public onMessage(topic: string, handler = SocketClientService.jsonHandler) : Observable<any> {
    return this.connect().pipe(first(), switchMap(client => { 
      return new Observable<any>(observer => {
        const subscription : StompSubscription = client.subscribe(topic, message => {
            observer.next(handler(message));
        });
        return () => {
          console.log("Unsubscribe from socket-client service");
          client.unsubscribe(subscription .id);
        }
      });
    }));
  }

In order to create an Observable, you can use new Observable or a creation operator.为了创建一个 Observable,你可以使用new Observable或创建操作符。 See the following example:请参阅以下示例:

const observable = new Observable(function subscribe(subscriber) {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);
});

You can provide a function unsubscribe() to allow dispose of resources, and that function goes inside subscribe() as follows:您可以提供一个函数unsubscribe()来允许处理资源,该函数在subscribe()内部如下:

const observable = new Observable(function subscribe(subscriber) {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.next(3);

  return function unsubscribe() {
    console.log('Clearing resources on observable');
  };
});

Of course, you can use an arrow function expression to have:当然,您可以使用箭头函数表达式来获得:

const observable = new Observable((observer) => {
  observer.next(1);
  observer.next(2);
  observer.next(3);

  return () => {
    console.log('Clearing resources on observable');
  };
});

Try the following code to test the Observable:尝试使用以下代码来测试 Observable:

const subscription = observable.subscribe(res => console.log('observable data:', res));
subscription.unsubscribe();

Finally, subscription.unsubscribe() is going to remove the socket connection in your example.最后, subscription.unsubscribe()将删除示例中的套接字连接。

Find a project running with these examples here: https://stackblitz.com/edit/typescript-observable-unsubscribe在此处查找使用这些示例运行的项目: https : //stackblitz.com/edit/typescript-observable-unsubscribe

Let me know if that helps!如果这有帮助,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM