Angular 5 使用RXJS进行$http轮询
创始人
2024-10-15 21:30:45
0

以下是一个使用Angular 5和RxJS进行$http轮询的解决方法,并包含代码示例:

首先,安装所需的依赖项:

npm install rxjs@6.5.5
npm install @angular/common@5.2.11
npm install @angular/core@5.2.11

然后,创建一个名为polling.service.ts的服务文件,并添加以下代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';

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

  poll(url: string, interval: number): Observable {
    return timer(0, interval).pipe(
      switchMap(() => this.http.get(url))
    );
  }
}

接下来,创建一个组件,例如名为polling.component.ts的组件,并添加以下代码:

import { Component, OnInit } from '@angular/core';
import { PollingService } from './polling.service';

@Component({
  selector: 'app-polling',
  template: `
    
{{ data | json }}
`, providers: [PollingService] }) export class PollingComponent implements OnInit { data: any; constructor(private pollingService: PollingService) {} ngOnInit() { const url = 'https://api.example.com/data'; // 根据实际情况替换为API的URL const interval = 5000; // 轮询间隔时间(毫秒) this.pollingService.poll(url, interval).subscribe( response => { this.data = response; }, error => { console.log('Error:', error); } ); } }

最后,在你的模块文件(例如,app.module.ts)中导入和声明该组件:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { PollingComponent } from './polling.component';

@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [PollingComponent],
  bootstrap: [PollingComponent]
})
export class AppModule {}

现在,你可以在应用程序中使用标签来使用该组件,并且它将从提供的URL中获取数据,并每隔指定的时间间隔进行轮询。

相关内容

热门资讯

玩家必备教程!pokermas... 玩家必备教程!pokermaster辅助器,约局吧德州可以透视吗,详细教程(有挂神器);科技安装教程...
热点推荐!hhpkoer辅助挂... 热点推荐!hhpkoer辅助挂是真的吗,wpk模拟器,2025新版技巧(有挂神器)是由北京得hhpk...
大神推荐!we poker插件... 大神推荐!we poker插件,wejoker黑侠辅助器,AI教程(有挂技巧)1、不需要AI权限,帮...
玩家必备科普!佛手大菠萝13道... 这是一款非常优秀的菠萝辅助器免费版的特点 ia辅助检测软件,能够让你了解到菠萝辅助器免费版的特点中牌...
最新技巧!约局吧如何查看是否有... 最新技巧!约局吧如何查看是否有挂,智星德州可以透视吗,黑科技教程(有挂透视);1.约局吧如何查看是否...
科技新动态!wepoker私人... 科技新动态!wepoker私人局可以透视,wejoker辅助机器人,AI教程(有挂攻略)科技教程也叫...
重大通报!aapoker辅助器... 重大通报!aapoker辅助器怎么用,德州局透视脚本免费版下载手机版,黑科技教程(有挂攻略);原来确...
一分钟了解!wepoker有辅... 一分钟了解!wepoker有辅助功能吗,德州局脚本,AI教程(有挂教程);玩家必备必赢加哟《1367...
今日头条!wepoker透视辅... 今日头条!wepoker透视辅助下载,佛手在线大菠萝为什么都输,2025教程(有挂攻略);最新版20...
科普分享!hhpoker有作弊... 1、科普分享!hhpoker有作弊的吗,拱趴大菠萝有什么挂,揭秘教程(有挂神器)。2、拱趴大菠萝有什...