Nikunj Guna
Nikunj Guna

Reputation: 21

How to correct this flow in latest Angular?

I have been working on this using latest Angular signals and rxResource, but came to this issue

  // 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'])
            })
          );
        })
      );
    }
  })

Issue here is that expList is getting each time, I need getstrategy for different expiry goal is

  1. On page load call explist once it's response came call getStrategy
  2. Do all subsequent call of getstrategy with simple myResource.reload() with selected expiry but dont make expiry api call.
  3. When lastLoadedScript changes repeat step 1. i.e: call exp then call get strategy

I tried seperate resource for exp but it won't work as getStrat must be call only after explist is available

Upvotes: 0

Views: 47

Answers (1)

Ravi Syaniya
Ravi Syaniya

Reputation: 5

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
  }
}

Key Points: 🔹 First Resource (expiryResource): Fetch the expiry list on initial load. Store it and use it for strategy calls. Reload the expiry list only when lastLoadedScript changes.

🔹 Second Resource (myResource): This resource will trigger the getstrategy API call based on the selected expiry, reusing the previously fetched expiryList data.

🔹 selectExpiry Function: Allows selection of a specific expiry. When an expiry is selected, it triggers the myResource.reload() method to fetch the strategy based on that expiry.

🔹 Efficient Re-fetching: The expiry list is only re-fetched when lastLoadedScript changes. After that, the strategy is fetched using the selected expiry without calling the expiry API again.

Upvotes: -1

Related Questions