代码之家  ›  专栏  ›  技术社区  ›  Nikson

如何在Angular4中每隔15分钟触发一个调用API的方法

  •  2
  • Nikson  · 技术社区  · 7 年前

    我在一个Angular4应用程序中工作,在这个应用程序中,我需要每隔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分钟调用一次这个方法。

    在恩戈尼尼特,我有以下几点

    import 'rxjs/add/observable/interval';
    
        this.call = Observable.interval(10000)
                    .subscribe((val) => { this.UPDATE_USER_SESSION() });
    

    有人能指导我解决这个问题吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   ZackDeRose    7 年前

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

    需要考虑的一些事项:

    很难从你的代码中分辨出发生了什么,但通常情况下,你与API的交互将包含在一个角度服务中,以封装你与该API的交互。(您应该可以在上面的解决方案链接中看到一个这样的例子。)我建议您创建一个新的服务来替换 END_USER_SESSION INSERT_USER_SESSION 功能。

    这个角度服务应该看起来像:

    @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 . 这将使你 插入会话 呼叫发生在 结束用户会话 调用(在上面的代码中,有一个竞赛条件,两个条件中的哪一个将首先发生)。

        2
  •  0
  •   Hrishikesh Kale    7 年前

    我想你可以用 Observable 为了这个

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

    像这样使用

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