Invoke the subscribe function within the encompassing parent function

In crafting a versatile method, I have devised the following code snippet:

fetchArticle(loading: Loading): void {
    this.articleService.getArticleById(this.data.definition.id)
      .map((response: any) => response.json())
      .subscribe((response: any) => {
        if (response.definition.is_purchased) {
          //additional instructions
          } else {
            //more instructions
          }
          loading.dismiss();
        } else {
           loading.dismiss();
        }
      }, () => { 
          loading.dismiss(); 
      });
  }

The method invoking this function looks like the following:

 myCallerFunction() {
     const loading = this.loader.create({
      content: 'loading...'
    });
    loading.present();

    this.fetchArticle(loading); //Can I place `loading.dismiss()` here? 
    }

To streamline the process, I am seeking advice on how to eliminate the loading parameter from the generic fetchArticle() method and move it within the parent function (myCallerFunction()) after resolving the subscription. Can you suggest a way to achieve this?

Answer №1

When dealing with an observable that terminates at a higher level, you must ensure to return an observable that can be accessed by the higher-level function.

One way to write this is:

getArticleById(loading: Loading) {
    const articles$ = this.articleService.getArticleById(this.data.definition.id)
      .map((res: any) => res.json());

    article$.subscribe((res: any) => {
        if (res.definition.is_purchased) {
          //more code
          } else {
            //more code
          }
    });

    return article$;  
}

The finally operator comes in handy as it:

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

myParentMethod(){
    const loading = this.loader.create({
      content: 'loading...'
    });
    loading.present();

    this.getArticleById().finally(() => loading.dismiss());
}

However, to improve the structure of the code, consider separating the logic for obtaining the observable from handling it. The revised code would look something like this:

getArticleById(): Observable<Article> {
    return this.articleService.getArticleById(this.data.definition.id)
      .map(res => res.json());
}

handleArticle(article) {
    if (article.definition.is_purchased) {
      //more code
    } else {
        //more code
    }
}

myParentMethod(){
    const loading = this.loader.create({
      content: 'loading...'
    });
    const article$ = this.getArticleById();

    loading.present();

    article$
      .finally(() => loading.dismiss())
      .subscribe(article => this.handleArticle(article));
}

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

Speed of scrolling on a biquadratic Bezier curve

I recently came across a fascinating website called that showcases a unique scrolling behavior. It gives the illusion of moving between slides (screens) with snappy scrolling, when in reality, the website actually scrolls continuously. The transitions bet ...

How does Typescript's dynamic tuple typing tool display all available options in Autocompletion/Intellisense?

Being new to TypeScript, I am facing an issue that I am unsure how to resolve. I want to generate a list of tuples from a list of components. Each tuple should consist of the component's name (keyof MyComponents) and its attributes. (Refer to the co ...

How can I iterate through the lines of a JSON file using javascript?

I am currently working with JSON data and need to extract specific information based on an ID. For example, if the ID is 1, I want to retrieve details like service1 and version 1.0. I am looking to create a loop that will iterate through each line of data ...

The Vue.js application is experiencing issues with displaying Google Maps functionalities

I have developed an application using Vue.js in Monaca and Cordova with onsenUI. My goal is to display my location on a Google map within the page. I attempted to achieve this by utilizing the npm package named vue2-google-maps, but unfortunately, it' ...

Checking for valid zip code using a regular expression in JavaScript

Thank you for the suggestions, everyone. I have made some modifications to the script based on your advice and it appears to be functioning correctly now. <script src="jquery-1.4.2.min.js" type="text/javascript"></script> <script> $ ...

Creating a Dynamic Tree View Component in AngularJS Using JSON Data

I am new to AngularJS and I need help creating a TreeView Structure from a JSON Object. Here is an example of my Return JSON Object: var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1}, {Name:'Item2', Childnod ...

When using Angular's .navigateByUrl() method, it successfully navigates to the desired page, however the html content is not

Whenever I try to navigate to the home page after logging in, I encounter an issue. I have a navbar <app-header></app-header> with two links - one for signing up and another for logging in. After successfully logging in, my goal is to navigate ...

Utilizing the @keypress event handler in VueJS

I am attempting to incorporate the onkeypress event within a Vue component. My goal is to allow only numbers on keypress while disallowing all other key codes. Here is what I have tried: Implementing the onkeypress event works perfectly! <input type=&q ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Revamping MapReduce in MongoDB Version 2.4

After upgrading to MongoDB 2.4, I encountered an issue with a map function that uses db, as mentioned in the release notes. The release notes suggest refactoring, but I am unsure about the best approach to take. The part of the function that is no longer ...

Generating dynamic @returns annotations in JSDoc based on the value of @param

How can I properly document the function in order for vscode-intellisense to recognize that getObject("player") returns a Player type and getObject("bullet") returns a Bullet type? /** * @param {string} type * @return {????} */ function getObject(type ...

The app.get() function seems to be inactive and not triggering in the Express application

I am currently exploring the MEAN stack and experimenting with implementing express. I've encountered a peculiar issue where I keep receiving a 404 error when trying to access a specific path that I have configured for the app object to manage. Oddly ...

AngularJs FileList Drag and Drop Feature

Being brand new to front-end development, I decided it would be a fun challenge to implement drag and drop functionality on an existing upload page. However, as I began integrating ng-flow (a directive that helps with drag and drop), I encountered difficul ...

Issue with integrating e-junkie shopping cart with Bootstrap 5

After transitioning from Bootstrap 4 to Bootstrap 5 and encountering navigation issues on smaller screens, I delved into the code to uncover the source of the problem. It turns out that the collapse button in the navbar wasn't functional due to confli ...

When using Laravel 5.2, JSON data is mistakenly returned as HTML

I've encountered an issue with ajax. My goal is to fetch all the records from a specific table using this ajax call: $('#chooseInvBtn').on('click', function(){ $.ajax({ type: "POST", url ...

The error message "TypeError XXX is not a function in NodeJS" indicates that

As I attempt to enhance the testability of my NodeJS API by incorporating a service, a peculiar issue arises. Specifically, upon injecting the service (class), an error is triggered stating that the method getTasks() does not exist. ROUTE const TodoServi ...

Can you explain the rule known as the "next-line" in TypeScript?

No code examples are available for the specific scenario described below: "next-line": [ true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace" ], ...

Utilize the ESLint plugin to manage unresolved import paths in Next.js modules

Utilizing module import from next and attempting to import a component as shown below: import Navbar from '@/components/Navbar/Navbar'; Upon running npm run lint, an error is returned stating: 1:20 Error: Unable to resolve path to module &apo ...

Can TypeScript ascertain the object's type dynamically based on the key of its proxy name?

I am creating a wrapper class that will handle various operations related to the user entity. These operations include checking if the user is a guest, verifying their permissions, and more. One of the functions I want to implement in this class is an acce ...

Coordinating Multiple Angular $http Requests using $q and Managing Errors with $q.catch

Struggling with understanding the correct utilization of Angular's $q and JavaScript's promise API. As a newcomer to Javascript, it's possible I'm making a syntax error. This question appears similar, but isn't an exact duplicate. ...