Having trouble with an Angular Service function that's not producing any results as expected? You might be attempting to make several http

Unfortunately, the website's structure requires me to retrieve data from various URLs where the same type of data in JSON format is located. These URLs are used for classification purposes, so I must retain them to categorize the data in the app. The service function below attempts to fetch data based on a set of topics, but it currently does not return anything:

getDataTopicItems(topicArray) {
    return this.items = topicArray.forEach((topic, i, topicArray) => {
        return this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
            .map(res => res.json())
            .map(items => items.d.results)
            .do(data => console.log(data))
            .concatMap(data => data)
      }
    )
}

I am subscribing to the function in the component template using *ngFor and an async pipe. What could be the issue in my implementation?

Update: I also attempted the following:

return this.http.get(this.baseUrl + topicArray[0] + this.policyOptions, this.options)
            .map(res => res.json())
            .map(items => this.policies = items.d.results)
            .do(data => console.log(data))
            .flatMap((policies) => topicArray.forEach((topic, i, topicArray) => {
                if (i < 0) {
                    this.http.get(this.baseUrl + topic + this.policyOptions)
                        .map(res => res.json())
                        .map(items => this.policies = items.d.results)
                        .do(data => console.log(data))
                }
            }))

Answer №1

When using the Array.forEach method, remember that the callback function does not expect to receive any arguments. If you intended to pass data to the function, you may want to consider using Array.map instead.

For a more RxJS-oriented approach, you can utilize the mergeMap operator like so:

return Observable.from(topicArray)
    .mergeMap(topic => this.http.get(this.baseUrl + topic + "/_api/Web/Lists/GetByTitle('What''s New')/items", this.options)
        .map(res => res.json())
        .map(items => items.d.results)
        .do(data => console.log(data))
        .concatMap(data => data);

Alternatively, consider using concatMap instead of mergeMap to ensure requests are processed in order, and replace .concatMap(data => data); with concatAll for clarity.

It's important to note that when you use this.items = ..., you're assigning an Observable to this.items, not the actual result.

Additionally, remember to subscribe to the returned Observable to access the results. For example:

getDataTopicItems([...]).subscribe(result => this.items = result);

Check out the live demo: https://jsbin.com/nuzifo/9/edit?html,js,console

Answer №2

Array.prototype.forEach typically yields undefined. For further information, you can refer to the documentation on MDN. Alternatively, consider utilizing Array.prototype.map which will transform this.items into an array of observables that can be manipulated to your liking.

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

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

Illuminating the method of retrieving the selected Checkbox value in Angular 2

I'm currently working on a basic To-Do list using Angular 2. I'm looking for a way to identify which checkbox the user has clicked and then apply a strikethrough effect to the text. It seems like I could utilize the :checked CSS property, but I&a ...

Introducing cutting-edge intellisense for Typescript Vue in VSCode, featuring automatic import functionality specifically designed for the

Currently, I am working on a small project using Typescript and Vue in VSCode. In my setup, I have TSLint, TSLint Vue, Vetur, and Prettier plugins installed. Unfortunately, I am facing an issue with the intellisense "auto import" feature. It does not seem ...

When it comes to form validations, I encounter an issue. I am able to view errors.minlength in the console, but for some reason, I am unable to access it

I would like the message "name is too short" to be displayed if last_name.errors.minlength evaluates to true. However, I encounter an error: Property 'minlength' comes from an index signature, so it must be accessed with ['minlength']. ...

Guide on how to update an array within typed angular reactive forms

I'm currently working on finding a solution for patching a form array in a strongly-typed reactive Angular form. I've noticed that patchValue and setValue don't consistently work as expected with FormControl. Here's an example of the fo ...

Angular2 Routing error. Index 1 in the requested path is undefined

Having trouble with routing in Angular 2. I am calling router.navigate from an action within a data table. The strange thing is that sometimes when I click the button to trigger this line, it works perfectly fine, but other times it doesn't. this.rou ...

Using setTimeout() does not work correctly when trying to call nested functions

I've written a timeout function that looks like this: setTimeout(this.logout, 1000); Here's the login method: logout() { this.auth_token = ""; this.loggedIn = false; this.emitLogedInStatusChange(); } isLoggedIn() { return this ...

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

Exploring disparities between the Client SDK and Admin SDK in conducting firestore queries

I am encountering difficulties with my query while running it in Firebase Functions. It functions perfectly on the client side, but fails to work in Functions. I am curious if there is a way to modify it to function with Admin SDK as well. Am I making any ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

Gridster2 for Angular: Resolving Overlapping Grid Items during Drag

The Angular version being used is 4.0.0 The angular-gridster2 library version being used is 2.10.0 When dragging the items randomly over other items, they become overlapped (as shown in the image below) The circled numbers represent the number of column ...

Angular version 6 and its routing functionality

Hey there, I need some help with setting up routers in my Angular app. Here is the code from my files: import {NgModule} from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const APP_ROUTES: Routes = [ {pa ...

The scale line on the OpenLayers map displays the same metrics twice, even when the zoom level is different

When using the Openlayers Map scale line in Metric units, a specific zoom rate may be repeated twice during the zoom event, even though the actual zoom-in resolution varies on the map. In the provided link, you can observe that the zoom rates of 5km and ...

How to customize Material UI Autocomplete options background color

Is there a way to change the background color of the dropdown options in my Material UI Autocomplete component? I've checked out some resources, but they only explain how to use the renderOption prop to modify the option text itself, resulting in a a ...

Error encountered in azure devops preventing successful execution: "npm ERR! code ELIFECYCLE"

I am facing an issue with my Azure DevOps build pipeline that contains 2 npm tasks: - one for npm install - and the other for npm run-script build Unfortunately, I am encountering errors that do not provide sufficient information about the root cause of ...

Informing typescript that an argument is specifically an array when accepting both a single string and an array of strings

How can I inform TypeScript that the code is functionally valid? It keeps suggesting it could be a string, but I am unsure how that would happen. Is this a bug in my code or am I inputting something wrong? For example: const i18nInstance = { options ...

angular triggering keyup event multiple times

Currently, I am working on a datalist feature. Whenever the user types something into the input field and releases a key, a GET request is made to retrieve an array of strings which are then displayed in the datalist. <input type="text (keyup)=&quo ...

How to Hide Parent Items in Angular 2 Using *ngFor

I am dealing with a data structure where each parent has multiple child items. I am trying to hide duplicate parent items, but accidentally ended up hiding all duplicated records instead. I followed a tutorial, but now I need help fixing this issue. I only ...

The pathway specified is untraceable by the gulp system

Hey there, I've encountered an issue with my project that uses gulp. The gulpfile.js suddenly stopped working without any changes made to it. The output I'm getting is: cmd.exe /c gulp --tasks-simple The system cannot find the path specified. ...

How can I determine which dist folder is utilized during the building of my App if an npm package contains multiple dist folders?

I have integrated an npm package called aurelia-google-maps into my application. This package includes various distribution folders such as AMD, System, CommonJS, Native Modules, and ES2015 within the /node_modules/ directory like so: /node_modules/ /a ...