How can we send a parameter to a subscribe function for retrieving the contents of an assets file in TypeScript and Ionic 3?

When working in TypeScript, I have discovered a way to retrieve the content of a text file from my assets directory using the following code:

this.http.get('assets/data/file_1.txt')
.subscribe(data=>{
   let obj = data['_body'];
   console.log("obj "+JSON.stringify(obj)); // This log displays the content of the file
});

Is it possible to include a parameter or value in this request?

For example, if I have multiple files (file_4.txt, file_5.txt, file_1.txt) and I want to loop through each of them, dynamically changing the file index. My current implementation is as follows:

var fileIndex=[4,5,1]; 
for (i = 0; i < this.fileIndex.length; i++) { 
  this.http.get('assets/data/file_'+this.fileIndex[i]+'.txt')
  .subscribe(data=>{
        let obj = data['_body'];
        console.log("obj "+JSON.stringify(obj));
        console.log("This is file number "+this.fileIndex[i]); // issue arises here
      });
}

Unfortunately, the file number cannot be logged for each request due to the asynchronous nature of the get request. The variable 'this.fileIndex[i]' returns "undefined" within the subscribe block. Is there a way to pass a parameter/value into the request to access it inside the subscribe function? Alternatively, how can I access the value of 'this.fileIndex[i]' within the subscribe function?

Answer №1

Here's a potential solution for extracting the full URL from data['url'] in the given context:

let indices = [4, 5, 1]; 
for (let index of indices) { 
  this.http.get('assets/data/file_' + index + '.txt', {
        params: { fileNumber: index }
    }).subscribe(response =>{
        let obj = response['_body'];
        console.log("Object: " + JSON.stringify(obj));
        console.log("File number: " +
this.extractQueryParamValue("fileNumber", response['url']));
      });
}

extractQueryParamValue = function (param, url) {
    var currentUrl = url ? url : window.location.href;
    var regex = new RegExp( '[?&]' + param + '=([^&#]*)', 'i' );
    var result = regex.exec(currentUrl);
    return result ? result[1] : null;
};

While functional, this approach may not be considered very elegant.

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

Execute .mts files using ts-node

Can ts-node be used to run .mts files? I attempted to do so, but encountered errors with imports (within the .mts file). Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. I am hesitant t ...

The ng-change event fails to trigger when the date change event is activated

Hey there, I'm new to working with AngularJS. I have a scenario where I want a method to be triggered when I change the date, opening a modal. However, when I use the ng-change event, the method is not called upon date change. If I switch to using ng- ...

Applying these sorting functions to my specific scenario

Hello everyone, I hope you can help me out with this issue. I have been struggling for hours trying to sort my array of objects in JavaScript based on a specific property, but I just can't seem to get it right. I have referred to some of the top post ...

What sets apart the function from the `=>` in TypeScript?

Currently, I am diving into the world of TypeScript and finding myself puzzled by the distinction between the keyword function and => (fat arrow). Take a look at the code snippet below: interface Counter { (start: number); interval: number; ...

What is the best way to implement type discrimination in TypeScript?

When using TypeScript with two interfaces combined as a union type, why doesn't it distinguish which type members can be declared? interface IFish { swim: () => void; } interface ICat { meow: () => void; } type Pet = IFish | ICat; const p ...

The function cannot be accessed during the unit test

I have just created a new project in VueJS and incorporated TypeScript into it. Below is my component along with some testing methods: <template> <div></div> </template> <script lang="ts"> import { Component, Vue } from ...

I'm attempting to retrieve mlab data in the console using node.js, but unfortunately encountering an error

I came across this helpful YouTube tutorial:https://www.youtube.com/watch?v=PFP0oXNNveg&t=460s. I followed the steps outlined in the video and made necessary code adjustments based on current updates found through a Google search (to resolve errors enc ...

The AOT Compilation error occurs in Angular2 RC6 when trying to call the function RouterModule.forChild(ROUTES) which is not supported

Operating Environment: Windows 10, IntelliJ 2016.2, node Angular Version: 2.0.0-rc.6 Language: [all | TypeScript X.X | ES6/7 | ES5] Typescript ES6 Node (for Ahead of Time Compilation issues): node --version = Node 4.4.7, NPM 3.10.6 The AOT com ...

Exploring the capabilities of combining Typescript with withStyles in the latest @material-ui/core framework

I have been working on updating some old Typescript code that was using material-ui@next to now use @material-ui/core. Typescript Version: 2.8.3 @material-ui/core: 1.1.0 I created a simple component that accepts a single prop, but when I try to use it, t ...

Leverage ngFor to loop through a "highly intricate" data structure

In my project, I have stored data in a JSON file structured as follows: { "name": { "source1": ____, "source2": ____, "source3": ____ }, "xcoord": { "source1": ____, "source2": ____, "source3": _ ...

How can I retrieve JSON data that is specific to the selected item in an Ionic Angular application?

Exploring the world of ionic-angular framework, I have a home page with a modal embedded within it. The home page displays a list of items fetched from a JSON file, and upon clicking on a specific item, I wish to display all the information related to that ...

Linting: Add "`··` eslint(prettier/prettier)" to a project using React with TypeScript and Styled Components

I'm facing a challenge with conflicting rules between Eslint and Prettier in my React project that uses TypeScript and Styled Components. When working in VSCode, I keep getting this error message: "Insert ·· eslint(prettier/prettier)" T ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...

Tips for managing promise rejection when generating a highland stream from a promise?

When working with [email protected] and [email protected] via typescript, the following code snippet is utilized: import * as highland from "highland"; import * as lodash from "lodash/fp"; const range = lodash.range(0, 10); const createPromise ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

Puppeteer: What is the best way to interact with a button that has a specific label?

When trying to click on a button with a specific label, I use the following code: const button = await this.page.$$eval('button', (elms: Element[], label: string) => { const el: Element = elms.find((el: Element) => el.textContent === l ...

Having trouble with React state not updating?

Hello, I am a beginner in the world of React and currently working on fetching an array of endpoints. My goal is to update the API's status every 15 seconds. Here is the code snippet for the array of endpoints: export const endpoints: string[] = [ " ...

Tips for maintaining knowledge after redirecting to a new page

Building an app using Ionic 4 where I need to display vouchers from a database as images. Each image should act as a link to a details page showing more information about that specific voucher. However, I am struggling to figure out how to keep track of th ...

Breaking up React code within the React.createElement() function

I am encountering an issue with lazily loaded pages or components that need to be rendered after the main page loads. When using createElement(), I receive the following error: LazyExoticComponent | LazyExoticComponent is not assignable to parameter of ty ...

Today is a day for coming together, not for waiting long periods of

When grouping by month and dealing with different days, I encountered an issue similar to the one shown in this image. https://i.stack.imgur.com/HwwC5.png This is a snapshot of my demo code available on stackblitz app.component.html <div *ngFor="let ...