The method of having two consecutive subscribe calls in Angular2 Http

Can the Subscribe method be called twice?

I am attempting to create an API factory that stores data in the factory and allows different components to use that data for each AJAX call.

The factory:

export class api {

    result = [];

    constructor (protected http: Http) { }

    getData ()
    {
        return this.http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
    }
}

A test component calling the subscribe method again:

export class TestPage {

    showListResult; 

    constructor (protected api: api) {

        this.api.getData().subscribe(res => this.showListResult = res)
    }

}

Answer №1

To create a new Observable wrapper, you can use the following code snippet:

import {Observable} from 'rxjs/Observable'

export class api {

    data = [];

    constructor (protected http: Http) { }

    fetchData () {
        return new Observable(observer => {
            this.http.get('./data.json')
                .map((res: Response) => res.json())
                .subscribe(res => {
                    this.data = res;
                    observer.next(res);
                    observer.complete();
                });
        });
    }
}

Answer №2

If you are looking to minimize HTTP requests by sharing the result with multiple subscribers, consider using a connectable observer that publishes and replays the last emitted value:

this.data = http.get('...').map(response=> response.json()).publishReplay().refCount();

Subsequent subscribers will receive the last value without triggering a new HTTP request.

Check out this Plunker demo.

This approach is similar to the one discussed in this Stack Overflow question and answer.

Answer №3

If you're using later versions, consider utilizing the .share() method from RxJs instead, which can be found at https://rxjs.dev/api/operators/share.

The use of .publishReplay().refCount(), as outlined by pixelbits, is now outdated and has been replaced by .share(). This allows for subscribing to the return data without having to call the method again.

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

Request for /Account after Keycloak token request in Angular app

I have been working on an Angular and Keycloak project. I followed a tutorial that helped me integrate Keycloak into Angular, which can be found here: https://www.npmjs.com/package/keycloak-angular My public client is able to request a token, but when it ...

Can JSON Web Tokens be utilized in a browser environment?

Searching for a way to parse the JWT token led me to this jsonwebtoken library https://www.npmjs.com/package/jsonwebtoken. It appears to be tailored for NodeJS. Is it feasible to utilize this library in the browser? My attempts so far have resulted in the ...

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

Angular is having trouble with the dropdown feature when using Semantic UI

I'm having trouble with the dropdown not displaying any items when I click on it. Here is the source code for reference: <div class = "ui centered grid"> <div class = "ten wide column"> <form class = "ui form"> <h4 cl ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...

Combining enum values to create a new data type

Exploring the implementation of type safety in a particular situation. Let’s consider the following: const enum Color { red = 'red', blue = 'blue', } const enum Shape { rectangle = 'rectangle', square = 'square ...

What are the steps for transitioning an Angular application from MonoRepo to PolyRepo?

Having created three separate Angular applications with individual workspaces, projects, and repositories, I am able to share modules among them using @angular-architects/module-federation. However, I am facing challenges when it comes to sharing component ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

Having trouble organizing the date strings in the material table column

In my Angular application, I have a material table with multiple columns that I am sorting using matSort. While I can successfully sort the last two columns in ascending or descending order, I am facing an issue with the first column which contains date va ...

Having difficulties establishing a connection with the websocket URL generated by Spark Java

I'm currently working on creating a websocket using the sparkjava framework. Here is the code snippet for setting up the websocket: public final class MainWS { static Map<Session, String> USER_SESSION_MAP = new ConcurrentHashMap<>(); stat ...

Trouble with 'import type' declaration causing build issues in a Next.js project

Having trouble importing the Metadata type from the next module. The code snippet below is directly from the Next.js documentation. THE ISSUE client.js:1 ./app/layout.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'r ...

Step-by-step guide to integrating Google AdSense ads.txt file into an Angular project

If you're experiencing problems with Google AdSense in your Angular project, it could be related to how static files are served within Angular and handled by servers. Let's go through the necessary steps to ensure that your ads.txt file is proper ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

The latest release of Angular2, rc1, eliminates all parameters that are not in

In the previous beta version, I was able to analyze using split Location.path(), but now it seems to have been removed. How can I prevent this removal? Interestingly, everything works well with matrix parameters (;id=123;token=asd). This was tested on a ...

What is the best way to retrieve the value from a chosen radio button?

Here is the HTML code snippet: <ion-list radio-group [(ngModel)]="portion" (ionChange)="getPortionType()"> <ion-list-header> Select Portion </ion-list-header> <ion-item *ngFor="let item of porti ...

How to access NavController in an Ionic2 service provider

In my Ionic2 app, I have created an AuthHttpProvider which acts as a wrapper for Http requests and automatically adds an authentication token (jwt) to each request. I use this instead of the default Http provider in all of my interactions with the server. ...

Ways to pass styling properties to a nested component

I am working on a component that includes an input field: <mat-form-field appearance="standard"> <mat-label >{{label}}<span>*</span></mat-label> <input [type]="type" <span matSuffix>{{suffix} ...

The GIPHY API object returns no results

Utilizing Angular 2 to fetch data from the GIPHY API. export class ListaGifsComponent { gifs : Object[] = []; urlBase = "http://api.giphy.com/v1/gifs/search?q="; termoPesquisado = "ryan+gosling"; key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn"; ...

Setting the selected value of a radio button in an edit form: a step-by-step

I'm currently developing an edit form using ReactiveFormModule. My goal is to display data in the edit form with various input elements such as textboxes, dropdowns, radio buttons, and checkboxes. I've been successful in setting values for textbo ...

Is there a way to locate all projects impacted by `nx`?

Currently, I am utilizing the nx tool to manage a mono repo specifically designed for typescript projects. The nx comes equipped with a command called affected, which allows me to focus solely on the changed project and any other projects that rely on it. ...