简体   繁体   English

RXJS 节流时间运算符在 Angular-RX.JS 中不起作用

[英]RXJS THROTTLETIME OPERATOR IS NOT WORKING IN ANGULAR-RX.JS

In my code I have function which calls the api. I want to throttle it someehow that the user cannot just keep on clicking the button to call the api.在我的代码中,我有 function,它调用 api。我想以某种方式限制它,用户不能继续单击按钮来调用 api。

Here is my function which calls the service这是我的 function 调用该服务

  public toggleFavorite(message: Message): void {
    const toggleMessageFavourite = new ToggleMessageFavouriteState(message.Id);
    this.messageService.toggleMessageFavourite(toggleMessageFavourite).subscribe(() => {
      message.Isfavourite = !message.Isfavourite;
    });
  }

In my service I have this code在我的服务中,我有这段代码

toggleMessageFavourite(model: ToggleMessageFavouriteState) {
    const url = `/Api/message/toggleMessageFavourite/`;
    return this.httpClient.post(url, model).pipe(
      throttleTime(5000)
    );
  }
}

I am expecting this function to throttle for 5 seconds before calling the next request.我期待这个 function 在调用下一个请求之前限制 5 秒。

It is not working since you are using the throttleTime operator in the pipe of a specific http request, that prevents more emission from the original observable but doesn't prevent new http requests.它不起作用,因为您在特定 http 请求的 pipe 中使用throttleTime运算符,这可以防止原始可观察到的更多发射,但不会阻止新的 http 请求。

One of the ways to achieve what you need is something like this:实现您需要的方法之一是这样的:

  toggledMessage$ = new Subject<toggleMessageFavourite >();

  public toggleFavorite(message: Message): void {
    const toggleMessageFavourite = new ToggleMessageFavouriteState(message.Id);
    
    this.toggledMessage.next(toggleMessageFavourite);
  
  }


 public exampleMethod(): void {
  this.toggledMessage$.pipe(throttleTime(5000))
  .subscribe(message => /* call api */ )
}

Of course, you need to call the exampleMethod initially in the ngOnInit .当然,您需要首先在 ngOnInit 中调用ngOnInit

You can also call the api in the switchMap operator and subscribe to the final result.也可以在switchMap算子中调用api订阅最终结果。

You're creating a new observable on every call to toggleMessageFavourite .您在每次调用toggleMessageFavourite时都会创建一个新的可观察对象。

throttleTime works on the values sent by an observable. throttleTime作用于可观察对象发送的值。

class Foo {
  subject$ = new Subject<string>();

  public constructor() {
    this.subject$.pipe(
      throttleTime(5000),
      switchMap((id: string) => {
        const toggleMessageFavourite = new ToggleMessageFavouriteState(message.Id);
        this.messageService.toggleMessageFavourite(toggleMessageFavourite)
      }).subscribe(() => {
        // 
      });
    )
  }

  public toggleFavorite(message: Message): void {
    this.subject$.next(message.Id);
  }
}

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

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