Utilize switchMap to sequence calls

My goal is to execute rest requests sequentially using switchMap(...) from RxJs.

Here is the object:

export class Transaction {
  constructor(
    public id: string,
    public unique_id: string,
    public name: string,
    public status: string,
    public type: string,
    public created_at: Date
  ) {}
}

This is the component:

@Component({
  selector: 'app-transaction-details',
  templateUrl: './transaction-details.component.html',
  styleUrls: ['./transaction-details.component.scss']
})
export class TransactionDetailsComponent implements OnInit {

  processingLogs: ProcessingLogs = new ProcessingLogs(null, null, null, null, null);
  transaction: Transaction;

  constructor(private transactionService: TransactionService,
              private processingLogsService: ProcessingLogsService,
              private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.params.pipe(
      flatMap(params => {
        if(params['id']) {
          return this.transactionService.get(params['id']);
        } else {
          return of(null);
        }
      })
    ).subscribe(value => {
      if(value != null) {
        this.transaction = value;
      }
    });

    this.route.params.pipe(
      flatMap(params => {
        if (transaction.unique_id) {
          return this.processingLogsService.getProcessingLogsList(transaction.unique_id);
        } else {
          return of(null);
        }
      })
    ).subscribe(value => {
      if (value != null) {
        this.processingLogs = value;
      }
    });
  }
}

I attempted the following approach:

this.route.params.pipe(
  tap( params => {
        if(params['id']) {
          return this.transactionService.get(params['id']);
        } else {
          return of(null);
        }
      }),
      switchMap( value => this.processingLogsService.getProcessingLogsList(value.unique_id) )
  )

Initially, I want to fetch

transactionService.get(params['id'])
using the id from the HTTP link. Then, once the Transaction object is retrieved, I aim to retrieve
getProcessingLogsList(transaction.unique_id)
utilizing the unique_id obtained from the initial request. However, my code attempt results in several errors and empty data when executed.

UPDATE: I performed a test with the following code but the page displayed no data:

const transactionService = (x) => of(`transaction ${x}`);
    const processLog = (x) => of(`logged ${x}`);

    this.route.params.pipe(
      switchMap(x=> transactionService(x).pipe(
        switchMap(x=>processLog(x))
      ))
    ).subscribe(x=>console.log(x));

Answer №1

One way to tackle this problem is by implementing a series of switchMap functions in a chain. Here's an example:

const userParams = of('123');
const dataService = (id) => of(`data for user ${id}`);
const logAction = (data) => of(`logged action: ${data}`);

userParams.pipe(
  switchMap(id => dataService(id).pipe(
    switchMap(data => logAction(data))
  ))
).subscribe(result => console.log(result));

Answer №2

After reading the @dK- 's response, have you experimented with a non-nested approach for chaining switchMap?

routeparams.pipe(
    switchMap(x=> transactionService),
    switchMap(x=>processLog)
).subscribe(x=>console.log(x));

Take a look here ->

EDITED

Would you be willing to attempt this? It's essentially the same method, but I've incorporated your original functions.

ngOnInit() {
  this.route.params.pipe(
    map(params=>params['id']),
    switchMap(idParameter=> this.processingLogsService.getProcessingLogsList)
  ).subscribe(logList=>
      console.log(logList)
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type 'myInterface' cannot be assigned to the type 'NgIterable<any> | null | undefined' in Angular

I am facing an issue that is causing confusion for me. I have a JSON data and I created an interface for it, but when I try to iterate through it, I encounter an error in my HTML. The structure of the JSON file seems quite complex to me. Thank you for yo ...

"Utilize Typescript for defining the parameter type in this

defineProperties(Element.prototype, { querySelector: { value: querySelectorPatched, writable: true, enumerable: true, configurable: true, }, querySelectorAll: { value(this: HTMLBodyElement): NodeListOf< ...

Angular 2: Dealing with Missing Image Loading

When viewing an HTML file containing the following code: <div> <img src="New-Google-Logo.png"/> </div> The image file New-Google-Logo.png is expected to load from the same folder as the HTML file. However, after running ng s ...

Can you explain Angular's "rule of unidirectional data flow" to me?

The concept of Angular's "unidirectional data flow rule" is mentioned throughout various sections of the Angular documentation, yet a clear and concise definition of this rule is nowhere to be found. After thorough research, I discovered two somewhat ...

Discover the use of dot notation for accessing nested properties

In the deps array below, I aim to enforce type safety. Only strings allowed should be in dot notation of ${moduleX}.${moduleX service} // Modules each have a factory function that can return a services object (async) createModules({ data: { factory: ...

Only map property type when the type is a union type

My goal is to create a mapping between the keys of an object type and another object, following these rules: Each key should be from the original type If the value's type is a union type, it should have { enum: Array } If the value's type is not ...

How can I import the googleapis library in Angular?

I'm currently working on integrating the Google Drive API into one of my projects. The Node.js quick start guide requires me to import file-reading and googleapis libraries. However, I've encountered some issues when trying to import them into ap ...

Ways to extract a Bearer Token from an Authorization Header using JavaScript (Angular 2/4)

When working with JavaScript, I have successfully implemented a method for authenticating to my server using an http post request. Upon receiving a response from the server, it includes a JWT in an Authorization header like this: Authorization: Bearer my ...

Instructions for designing a Loading Indicator or Progress Bar within the App Directory of NextJS

Having built a substantial web application using NextJS 13, I initially utilized the Pages Router. However, as I neared completion of the website, I decided to make the switch to the App Directory. The primary motivation behind this migration was not just ...

How to easily upload zip files in Angular 8

Currently, I am working on integrating zip file upload feature into my Angular 8 application. There are 3 specific requirements that need to be met: 1. Only allow uploading of zip files; display an error message for other file types 2. Restrict the file s ...

What is the reason that the command `npx create-react-app my-app --typescript` is not providing me with the expected TypeScript files?

I used the command npx create-react-app my-app --typescript to create my React project, but it seems like I still ended up with the default JavaScript boilerplate files. I was expecting to see files with a .tsx or .ts extension and use import * from as R ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Retrieving the checked value of a checkbox in Angular instead of a boolean value

Currently I am working on a project using ServiceNow and AngularJS. I am having trouble obtaining the value of a checkbox. Here is the code snippet: $scope.userFavourite = function(favourite){ alert(favourite); } <labe for="tea"& ...

Issue with typescript in Material-UI Next

I encountered an error while trying to integrate material-ui-next component into a default VS2017 react-redux template. The error message reads as follows: ERROR in [at-loader] ./node_modules/material-ui/BottomNavigation/BottomNavigationButton.d.ts:6:74 T ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

Curious about the missing dependencies in React Hook useEffect?

I'm encountering the following issue: Line 25:7: React Hook useEffect has missing dependencies: 'getSingleProductData', 'isProductOnSale', and 'productData'. Either include them or remove the dependency array react-hoo ...

What is the best way to refresh the script located within the head tag of an index.html file in an Angular

I've been looking for solutions, but I can't seem to find one. In my index.html file, I've placed some script within the head tag (even above the </body> tag) and included a $(document).ready function. The issue I'm facing is th ...

Can we modify the auto-import format from `~/directory/file` to `@/directory/file`?

I have a small issue that's been bugging me. I'm working on a project using Nuxt3 and Vscode. When something is auto-imported, Vscode uses the ~/directory/file prefix instead of the preferred @/directory/file. Is there an easy way to configure Vs ...

Dynamic form controls within Angular are constantly changing and adapting

On my preference screen, users can sign up for various services that are received from a service provider. The Json data structure looks something like this: [ { category : 'General', source : [ { name: 'ABC News', ...

Can we specify the type of a destructured prop when passing it as an argument?

I have implemented Material UI's FixedSizeList which requires rendering rows in the renderRow function and passing it as a child to the component. The renderRow function accepts (index, style, data, scrolling) as arguments from the FixedSizeList comp ...