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));