如何在最新的 Angular 中纠正此流程?

问题描述 投票:0回答:1

我一直在使用最新的 Angular 信号和 rxResource 来解决这个问题,但遇到了这个问题

  // this will make API call for chain everytime lastLoadedscript is set
  myResource = rxResource<{ [key: string]: strategy[] }, { seg: number, sid: number }>({
    request: () => {
      let script = this.stateService.lastLoadedScript()
      let tempReq = {
        seg: script.id || 0,
        sid: script.sid
      }
      return tempReq
    },
    loader: ({ request }) => {
      return this.myService.getExplist(request).pipe(
        switchMap((expiryDetails: ExpiryDetails[]) => {
          this.expiryList = expiryDetails;
          this.expirySortname = this.expiryList.map(e => e.sortname);
          let script = this.stateService.lastLoadedScript();
          let tempObj = {
            "StrategyName": "*",
            "Symbol": script.name,
            "ExpiryJulian": this.expiryList[this.prebuiltExpiry()].expiry
          };
          return this.myService.getstrategy(tempObj).pipe(
            map(resp => {
              if (resp['status'] != 'success') {
                throw new Error('Invalid resp');
              }
              return processData(resp['data'])
            })
          );
        })
      );
    }
  })

这里的问题是 expList 每次都会获取,我需要不同到期时间的 getstrategy 目标是

  1. 页面加载时调用 explist,一旦响应到达,调用 getStrategy
  2. 使用简单的 myResource.reload() 执行 getstrategy 的所有后续调用,并选择到期时间,但不要进行到期 api 调用。
  3. 当lastLoadedScript更改时,重复步骤1。即:调用exp然后调用get策略

我尝试为 exp 提供单独的资源,但它不起作用,因为只有在 explist 可用后才必须调用 getStrat

javascript angular angular-signals
1个回答
0
投票
Try this --->

import { rxResource } from 'rx-resource';
import { switchMap, map } from 'rxjs/operators';

class MyComponent {`enter code here`
  expiryList: ExpiryDetails[] = [];
  expirySortname: string[] = [];
  selectedExpiry: number = -1;  // Store selected expiry
  myResource: any;

  constructor(private myService: MyService, private stateService: StateService) {
    this.initializeResources();
  }

  // Initialize the resources
  initializeResources() {
    // First resource to load the expiry list
    const expiryResource = rxResource<ExpiryDetails[], any>({
      request: () => {
        const script = this.stateService.lastLoadedScript();
        return { seg: script.id || 0, sid: script.sid };
      },
      loader: ({ request }) => {
        return this.myService.getExplist(request).pipe(
          map((expiryDetails: ExpiryDetails[]) => {
            this.expiryList = expiryDetails;
            this.expirySortname = this.expiryList.map(e => e.sortname);
            return expiryDetails;  // Return the expiry details
          })
        );
      }
    });

    // Second resource to get strategy based on selected expiry
    this.myResource = rxResource<{ [key: string]: strategy[] }, { seg: number, sid: number, expiry: number }>({
      request: () => {
        const script = this.stateService.lastLoadedScript();
        return {
          seg: script.id || 0,
          sid: script.sid,
          expiry: this.selectedExpiry || this.expiryList[this.prebuiltExpiry()]?.expiry // Default to prebuiltExpiry if not selected
        };
      },
      loader: ({ request }) => {
        return this.myService.getstrategy({
          StrategyName: "*",
          Symbol: this.stateService.lastLoadedScript().name,
          ExpiryJulian: request.expiry
        }).pipe(
          map((resp) => {
            if (resp['status'] !== 'success') {
              throw new Error('Invalid response');
            }
            return processData(resp['data']);
          })
        );
      }
    });

    // Trigger the first resource to load expiry list initially
    expiryResource.load().subscribe();

    // Set up a listener or mechanism to watch for changes in lastLoadedScript
    this.stateService.onLastLoadedScriptChange().subscribe(() => {
      expiryResource.reload().subscribe(); // Reload expiry list when lastLoadedScript changes
    });
  }

  // Function to select a different expiry and trigger strategy call
  selectExpiry(expiry: number) {
    this.selectedExpiry = expiry;
    this.myResource.reload().subscribe(); // Call getstrategy with new expiry
  }

  prebuiltExpiry() {
    // Provide the prebuilt expiry index or logic
    return 0;  // Adjust as needed
  }
}

要点: 🔹 第一个资源(expiryResource):在初始加载时获取过期列表。存储它并将其用于策略调用。仅当 LastLoadedScript 更改时才重新加载过期列表。

🔹第二个资源(myResource):该资源将根据所选的到期时间触发 getstrategy API 调用,重用之前获取的 expiryList 数据。

🔹 selectExpiry 功能:允许选择特定的到期时间。当选择到期日时,它会触发 myResource.reload() 方法以根据该到期日获取策略。

🔹高效重新获取:仅当lastLoadedScript更改时才重新获取过期列表。之后,使用选定的到期时间获取策略,而无需再次调用到期 API。

© www.soinside.com 2019 - 2024. All rights reserved.