【问题标题】:How to trigger a method to call an API in every 15 minutes interval in Angular4如何在Angular4中每15分钟触发一次调用API的方法
【发布时间】:2018-10-30 17:33:31
【问题描述】:

我在一个 Angular 4 应用程序中工作,在这个应用程序中,我需要每隔 15 分钟调用一次 API。我阅读了一些 stackoverflow 帖子,但我无法得到我正在寻找的内容。

这是我迄今为止尝试过的。

 UPDATE_USER_SESSION() {

        this.publicIp.v4().then(ip => {
            this.END_USER_SESSION(ip)
        })

        this.publicIp.v4().then(ip => {
            this.INSERT_USER_SESSION(ip)
        })
    }

我在 ngOnInit 之外有这个方法。我想每隔 15 分钟调用一次这个方法。

在 ngOnInit 里面我有以下

import 'rxjs/add/observable/interval';

    this.call = Observable.interval(10000)
                .subscribe((val) => { this.UPDATE_USER_SESSION() });

谁能指导我解决这个问题。

【问题讨论】:

  • 您是否尝试过每 15 分钟应用超时或超时?称它为 this.sub = Observable.interval(10000) .subscribe((val) => { console.log('call'); } 并停止 this.sub.unsubscribe(); 从stackoverflow.com/questions/46096587/…
  • 我怀疑你打错字请检查你写的是ngOnInt还是ngOnInit,交叉验证。
  • 这是一个拼写错误@Make

标签: angular


【解决方案1】:

看到您对我对this 的回答的评论。我认为这本质上是一样的(只有我的示例显示 API 每 10 秒而不是 15 分钟被点击一次(15*60*1000= 900000)。

需要考虑的一些事项:

很难从您的代码中看出发生了什么,但通常情况下,您与 API 的交互将包含在 Angular 服务中,以封装您与该 API 的交互。 (您应该能够在上面的解决方案链接中看到一个示例。)我建议创建一个新服务来替换您的 END_USER_SESSIONINSERT_USER_SESSION 函数。

Angular 服务应该看起来像:

@Injectable()
export UserSessionService {
  constructor(private http: HttpClient) {}

  public endUserSession(ip: string): Observable<void> {
    // use the HttpClient to hit the API with the given IP
  }

  public insertUserSession(ip: string): Observable<void> {
    // use the HttpClient to hit the API with the given IP
  }
}

那么你的组件代码应该是这样的:

@Component({
  //...
})
export class YourComponent implements OnInit, OnDestroy {
  private alive: boolean;
  private publicIp = require('public-ip');

  constructor(private userSessionService: UserSessionService){}

  ngOnInit(){
    this.alive = true;
    TimerObservable.create(0, 900000)
      .pipe(
        takeWhile(() => this.alive)
      )
      .subscribe(() => {
        this.publicIp.v4().then(ip => {
          this.userSessionService.endUserSession(ip).subscribe(() => {
            this.userSessionService.insertUserSession(ip).subscribe(() => {
              // do nothing
            });
          });
        });
      });
  }

  ngOnDestroy(){
    this.alive = false;
  }
}

注意insertUserSession 调用在subscribe() 内的嵌套 的endUserSession。这将使您的insertUserSession 调用在您的endUserSession 调用之后发生(在您上面的代码中,有一个竞争条件,这两个将首先发生)。

【讨论】:

  • 不用担心。乐于助人!
【解决方案2】:

我认为您可以为此使用Observable

需要导入import 'rxjs/add/observable/interval';

并像使用一样

this.obs = Observable.interval(10000)
    .subscribe((val) => { console.log('called'); }

【讨论】:

    猜你喜欢
    • 2018-05-11
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多