简体   繁体   English

如何在不订阅的情况下使用 Debounce Time

[英]How to use Debounce Time without subscribing to it

i have a Service witch extends TitleService witch have this method我有一个 Service witch extends TitleService witch 有这个方法

setTitle(newTitle: string) {
    super.setTitle(newTitle+'TEST');
}

I wanted to set the Title after 2 seconds after the method is called, using debounceTime but i dont want to subscribe to it.我想在调用方法后 2 秒后使用 debounceTime 设置标题,但我不想订阅它。

The reason why i need DebounceTime is beacuse if the user trigger the events countles times, then the title would be the last one.我需要 DebounceTime 的原因是如果用户触发事件无数次,那么标题将是最后一个。

Is there any solution?有什么解决办法吗?

You could use a Subject in your CustomTitleService:您可以在 CustomTitleService 中使用 Subject:

import { Injectable } from '@angular/core'
import { Title } from '@angular/platform-browser'
import { Subject } from 'rxjs'
import { debounceTime, startWith } from 'rxjs/operators'

@Injectable({
  providedIn: 'root'
})
export class CustomTitleService {
  titleSubject = new Subject<string>()

  constructor(
    private titleService: Title
  ) {
    this.titleSubject
      .pipe(
        startWith(this.titleService.getTitle()),
        debounceTime(2000) // adjust, here it's 2 sec
      )
      .subscribe(title =>
        this.titleService.setTitle(title)
      )
  }

  setTitle(newTitle: string) {
    this.titleSubject.next(`${newTitle} TEST`)
  }
}

Note that in the official Angular documentation, it is noted that the class Title is final and hence should not be extended.请注意,在官方 Angular 文档中,class Title 是最终的,因此不应扩展。 This is why I've maded the CustomTitleService be a wrapper of the Title service instead: https://angular.io/api/platform-browser/Title这就是为什么我将 CustomTitleService 改为标题服务的包装器: https://angular.io/api/platform-browser/Title

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

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