How can I apply concatMap in Angular?

Can you please guide me on how to effectively utilize concatMap with getPrices() and getDetails()?

   export class HistoricalPricesComponent implements OnInit, OnDestroy {
        private unsubscribe$ = new Subject < void > ();
    
        infoTitle: string = "";
        lines: HistoryPoint[] = [];
    
        model: Currency = new Currency();
        svm: string;
    
        constructor(
            private location: Location,
            private service: HistoricalPricesService,
            private activatedRoute: ActivatedRoute
        ) {}
    
        ngOnInit(): void {
            let svm: string | null;
            svm = this.activatedRoute.snapshot.paramMap.get('svm');
            if (!svm) {
                this.goBack();
                return;
            }
            this.svm = svm;
    
    
            this.getPrices();
            this.getDetails(svm)
        }
    
        ngOnDestroy(): void {
            this.unsubscribe$.next();
            this.unsubscribe$.complete();
        }
    
        getPrices(): void {
            this.service.getInstrumentHistoryEquities(this.svm, this.model).pipe(
                takeUntil(this.unsubscribe$)
            ).subscribe(res => {
                if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
                    if (res.HISTO.POINT.length > 0) {
                        this.lines = res.HISTO.POINT.reverse();
                    }
                }
            });
        }
    
        getDetails(svm: string): void {
            this.service.getInstrumentInfo(svm).pipe(
                takeUntil(this.unsubscribe$)
            ).subscribe(res => {
                if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
                    this.infoTitle += " " + res.ADVTITRE.BASIQUETITRE.LABEL + " (" + res.ADVTITRE.BASIQUETITRE.PLACELABEL + ")";
                }
            });
        }
    
        goBack(): void {
            this.location.back();
        }
    }

I attempted to reference this page

However, I am unsure about where to begin?

The example provided does not clarify on how to implement this effectively?

Answer №1

Here is a solution that involves the use of the `concatMap` operator in a stream. In this approach, two Subject instances are initialized for performing actions like fetching prices and details.

The AJAX calls are made using the `concatMap` strategy to ensure proper ordering, and the results are then converted into Observables for further processing or direct usage in the component's template.

   export class HistoricalPricesComponent implements OnInit, OnDestroy {
        private unsubscribe$ = new Subject<void>();
    
        // Variables
        infoTitle: string = "";
        lines: HistoryPoint[] = [];
        model: Currency = new Currency();
        svm: string;
    
        // Actions
        getPrices$ = new Subject<void>();
        getDetails$ = new Subject<string>();
        
        // States
        prices$: Observable<any>();
        details$: Observable<any>();
        
        constructor(
            private location: Location,
            private service: HistoricalPricesService,
            private activatedRoute: ActivatedRoute
        ) {}
    
        ngOnInit(): void {
            let svm: string | null;
            svm = this.activatedRoute.snapshot.paramMap.get('svm');
            if (!svm) {
                this.goBack();
                return;
            }
            this.svm = svm;
    
            this.prices$ = this.getPrices$.pipe(concatMap(this.getPrices));
            this.details$ = this.getDetails$.pipe(concatMap((svm => this.getDetails(svm)));
    
        }
    
        ngOnDestroy(): void {
            this.getPrices$.complete()
            this.getDetails$.complete()
            this.unsubscribe$.complete();
        }
    
        getPrices(): void {
            this.service.getInstrumentHistoryEquities(this.svm, this.model).pipe(
                takeUntil(this.unsubscribe$)
            ).subscribe(res => {
                if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
                    if (res.HISTO.POINT.length > 0) {
                        this.lines = res.HISTO.POINT.reverse();
                    }
                }
            });
        }
    
        getDetails(svm: string): void {
            this.service.getInstrumentInfo(svm).pipe(
                takeUntil(this.unsubscribe$)
            ).subscribe(res => {
                if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
                    this.infoTitle += " " + res.ADVTITRE.BASIQUETITRE.LABEL + " (" + res.ADVTITRE.BASIQUETITRE.PLACELABEL + ")";
                }
            });
        }
    
        goBack(): void {
            this.location.back();
        }
    }

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

Can you explain the contrast between the @HostBinding() directive and ElementRef/Renderer in Angular?

I'm currently in the process of developing a directive for a dropdown toggle feature. Through my research, I have come across two different approaches to implement this directive. Which method would be considered the most effective practice? Approach ...

What is the best approach to integrate react-hooks, redux, and typescript seamlessly?

Struggling to seamlessly integrate React-hooks, Redux, and Typescript. It's a never-ending cycle of fixing one error only for another to pop up. Can anyone pinpoint what the root issue might be? Currently facing the following error related to my red ...

Order of custom code and JQuery in ASP master page

Using an ASP master page to include all the Javascript and jQuery files has presented a challenge for me. Specifically, the jQuery function in OrderManagement.js $(".menu-item").click(function () { window.alert("some text"); }); fails to execute whe ...

"The printing function of the "Print page" button appears to be malfunctioning

I am having some trouble with my JavaScript code for a "print page" button in an HTML document. The button appears and is clickable, but it doesn't actually print the page as intended. I keep receiving 3 errors related to the `document` object being u ...

What is TS's method of interpreting the intersection between types that have the same named function properties but different signatures (resulting in an error when done

When working with types in Typescript, I encountered an interesting scenario. Suppose we have a type A with two properties that are functions. Now, if we define a type B as the intersection of type A with another type that has the same function properties ...

Navigating between interfaces without the need to constantly refresh or reload

Currently, I am in the process of developing a website using ASP.NET MVC that allows users to navigate between pages without refreshing each time. My approach involves treating views as 'areas' or mini master pages, utilizing partial views inste ...

What makes TS unsafe when using unary arithmetic operations, while remaining safe in binary operations?

When it comes to arithmetic, there is a certain truth that holds: if 'a' is any positive real number, then: -a = a*(-1) The Typescript compiler appears to have trouble reproducing arithmetic rules in a type-safe manner. For example: (I) Workin ...

Can a Set (or Map) be held in a "frozen" state?

Despite the fact that Set is an Object, Object.freeze() specifically operates on the properties of the object, a feature not utilized by Map and Set: for example let m = new Map(); Object.freeze(m); m.set('key', 55); m.get('key'); // == ...

On a mobile device, the keyboard is hiding the PrimeNG dropdown

While my dropdown works flawlessly on a desktop browser, I encountered an issue when accessing it on an Android device. The dropdown immediately disappears and the virtual keyboard pops up, which is not the case on iOS devices. I suspect that the problem ...

Unit Testing AngularJS Configuration in TypeScript with Jasmine

I'm in the process of Unit Testing the configuration of a newly developed AngularJS component. Our application uses ui-router for handling routing. While we had no issues testing components written in plain Javascript, we are encountering difficulties ...

Unable to remove spaces in string using Jquery, except when they exist between words

My goal is to eliminate all white spaces from a string while keeping the spaces between words intact. I attempted the following method, but it did not yield the desired result. Input String = IF ( @F_28º@FC_89º = " @Very strongº " , 100 , IF ( @F_28 ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Adjusting color of fixed offcanvas navbar to become transparent while scrolling

After creating a navbar with a transparent background, I am now using JavaScript to attempt changing the navigation bar to a solid color once someone scrolls down. The issue is that when scrolling, the box-shadow at the bottom of the navbar changes inste ...

Error: Unable to execute decodeHtml because it is not recognized as a function

After transitioning to VueJS 2, I encountered a challenge. While using a filter that calls a custom function, I received the error message: TypeError: this.decodeHtml is not a function Below is my code snippet: new Vue({ el: '#modal' ...

The getJSON function yields a null value

When using the jQuery getJSON function, I am getting a null response even though everything seems to be written correctly: $.getJSON("/site/ajax/autocomplete/key", function(data) { alert(data); //null alert(data.term); //null }); I am working wit ...

Ways to verify the presence of isBrowser in Angular 4

Previously, isBrowser from Angular Universal could be used to determine if your page was being rendered in a browser (allowing for usage of features like localStorage) or if it was being pre-rendered on the server side. However, it appears that angular2-u ...

The image in drag and drop ghost preview is not appearing on Firefox

I want to show a ghost element instead of the default browser preview while dragging and dropping. However, in Firefox, the image inside the ghost element is not displayed during dragging. Oddly enough, if I drop it and then drag again, the image does appe ...

What methods can be utilized to accurately determine a user's online status without continuously sending AJAX requests to the server through setInterval?

Seeking effective methods to determine a user's online status I am currently employing an inefficient technique to address this issue: I continuously send AJAX requests to the server at set intervals using setInterval, allowing the server to gauge th ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Efficient method for managing complex JSON object updates using setState in React

My task involves handling structured data in JSON format, which I am unable to modify due to API restrictions. The challenge is to update the JSON file based on user modifications. { "id": 1269, "name": "Fet", &quo ...