如何创建自动轮询服务以使数据在 Angular 中保持最新

How do I create an automatic polling service to keep data up to date in Angular

我是 Angular 的新手,我无法弄清楚如何使用按时间间隔设置的 API 请求自动刷新服务数据。这是有问题的服务,我打算在给定计时器上更新 shopPreferences 字段:

@Injectable({ providedIn: 'root' })
export class ShopManagerService {
    private shopPreferences: ShopPreferences = null;

    setPreferences(shopPreferences: ShopPreferences) {
        this.shopPreferences = shopPreferences;
    }

    isDeliverySlotsActive(){
        if(this.shopPreferences == null || this.shopPreferences.delivery_slots == null) return;
        return this.shopPreferences.delivery_slots;
    }

    getCurrencySymbol(){
       if(this.shopPreferences == null || this.shopPreferences.currency_display_symbol == null) return;
       return this.shopPreferences.currency_display_symbol;
    }
    ...
    // more data getters
}

截至目前,此 shopPreferences 字段是在某个组件初始化时设置的,使用单独的 ApiManagerSerivce,如下所示:

@Injectable({ providedIn: 'root' })
export class ApiManagerService {

    private token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MjcwMjA3MiwidGltZXN0YW1wIjoiMjAyMS0wNC0wOSAwOToxNToxNS4';

    constructor(private http: HttpClient) {}

    fetchShopPreferences(id: string) {
        const url = "https://commerce.ww-api.com/commerceapi/v1/front/front_url/" + id + "/";
        return this.http
            .get<ShopPreferences>(url, {
                headers: new HttpHeaders({
                    token: this.token,
                }),
            });
    }
    ...
    // more api requests
}

我如何转换我的代码,以便 ShopManagerService 可以处理 API 请求并使 shopPreferences 对象保持最新状态,间隔时间为 - 比如 - 2 分钟?

也许尝试这样的事情,同时删除对 fetchShopPreferences 的现有调用。您必须为间隔设置 id 属性 才能知道用于获取调用的内容(或者如果它是静态的,则直接将其作为参数提供):

@Injectable({ providedIn: 'root' })
export class ApiManagerService {

    private token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MjcwMjA3MiwidGltZXN0YW1wIjoiMjAyMS0wNC0wOSAwOToxNToxNS4';

    public id: string; // Update this where/when you need to

    constructor(private http: HttpClient, private shopManagerService: ShopManagerService) {
      interval(120000).pipe(
        switchMap(() => fetchShopPreferences(this.id).pipe(
          first())
        )
      )
      .subscribe((res) {
        shopManagerService.setPreferences(res);
      });
    }

    fetchShopPreferences(id: string) {
        const url = "https://commerce.ww-api.com/commerceapi/v1/front/front_url/" + id + "/";
        return this.http
            .get<ShopPreferences>(url, {
                headers: new HttpHeaders({
                    token: this.token,
                }),
            });
    }
    ...
    // more api requests
}