Having trouble consuming data from a service in Angular 6?

I'm in the process of creating a basic cache service in Angular; a service that includes a simple setter/getter function for different components to access data from.

Unfortunately, when attempting to subscribe to this service to retrieve the data, the subscribe callback is never triggered and the data remains unretrievable.

catch-service.service.js


import { Injectable } from '@angular/core';
import { Observable, from } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CacheService {

  cacheData: Observable<any>;

  constructor() { }

  setCacheData(data) {
    this.cacheData = new Observable(data);
  }

  getCacheData(): Observable<any> {
    return from(this.cacheData);
  }
}

component.component.js


...
export class SomeComponent {

  constructor(private cacheService: CacheService) { }

  data = null;

  ngOnInit() {
    this.cacheService.getCacheData().subscribe(resp => {
      console.log(resp);
      this.data = resp;
    });
  }
...

The service has been injected into the module class without any compilation errors. However, the expected data does not get assigned to the component.

Answer №1

If you want to implement caching in Angular, you can follow this code snippet:

export class CacheService {

     // Define a method to set and get the cache 
     cacheData: Observable<any>
     setCache: (cachedata: any) {
          var newObservable = new Observable(observer => {
            observer.next(cachedata);
            observer.complete();
          });
          this.cacheData = newObservable;

    }
    
    getCacheData(): Observable<any>{
        return this.cacheData;
    }

In your component, you can subscribe to the cached data like this:

service.getCacheData().subscribe((data) => {
    // You will receive the cached data here
});

For further understanding of how Observables work in Angular, you can refer to this Stack Overflow answer:

How create observable with parameters in Angular 6?

Answer №2

To successfully execute this code snippet, make sure you have data stored in the cacheData.

Here's an illustration:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {

  cacheData: Observable<any> = new Observable(observer => {
    observer.next(1)
    observer.next(2)
    observer.next(3)
    observer.next(4)
  })

  ngOnInit() {
    this.cacheData.subscribe(
      (data) => {
        console.log(data)
      }
    )
  }
}

Within this code block, a new Observable is created using the ngrx library integrated into Angular.

You then proceed to define and assign values that will be consumed (via observer.next()) when subscribing to the cacheData property.

observer.next() supports various arguments such as:

  • Boolean
  • Number
  • String
  • Function
  • Object
  • Array
  • null
  • undefined

For further insights, visit .

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

What is the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

Exploring the process of authentication and authorization at individual route levels within Angular 4 using Keycloak

We have successfully integrated Keycloak with our application and the login and logout flow is functioning properly. However, we are facing an issue with authentication and authorization at the route level. When a user clears their browser session or the s ...

An issue with the Pipe searchByType is resulting in an error stating that the property 'type' is not found on the type 'unknown'

I keep encountering a range of errors like roperty does not exist on type 'unknown' after running the command ionic build --prod --release src/app/pages/top-media/top-media.page.ts:18:16 18 templateUrl: './top-media.page.html', ...

The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far: // Triggere ...

The application was not functioning properly due to an issue with the getSelectors() function while utilizing @ngrx/entity to

Currently, I am facing an issue with implementing a NgRx store using @ngrx/entity library. Despite Redux Devtools showing my collection loaded by Effect() as entities properly, I am unable to retrieve any data using @ngrx/entity getSelectors. Thus, it seem ...

Struggling to assign the correct data type to a property in Typescript

I am encountering a TypeScript error with the following code. In this interface, the 'items' property can be either an object or an array depending on the code and response. I am unsure how to specify the datatype of 'array/object/any', ...

Concealing forms within an Angular 5 application

I'm currently working on displaying the terms of use on the initial screen along with two buttons. If the user clicks the accept button, they will be directed to the authentication form. However, if they click refuse, the "Refused Terms" screen will a ...

Properties cannot be accessed using the standard method in the controller; however, they function correctly when using an arrow

Currently, I am facing a challenge where traditional class methods do not allow me to access the userService. I aim to write typical class methods in my user controller like this: public async register(req: Request, res: Response, next: NextFunction): Pr ...

Exploring the functionalities of React Native with react-hook-form and implementing them with TypeScript

I've been working on creating a custom Input component in react native using typescript for the react-hook-form library. type CustomInputProps = { name: any, control: any } const CustomInput: FC<CustomInputProps> = ({name, control, ...p ...

What could be the reason for the discrepancy between my get_token() function and the value obtained from request.META.get("CSRF_COOKIE")?

Can anyone shed light on why I'm facing this particular issue? I am currently exploring the integration of Angular 17 as a Frontend with Django as a Backend. While validating a form, I encountered an issue where the token obtained from Django does no ...

Angular universal triggers an "Error at XMLHttpRequest.send" issue

After updating my project to Angular 10 and incorporating angular universal, I encountered a strange error. While the application builds without any issues, I face an error when trying to run it on my development environment: ERROR Error at XMLHttpReque ...

Angular 6 form input value displays incorrectly after dynamically closing a tab

After adding a child-component with a form inside a tab, I noticed that when I closed the tab, the child-component form value was changed to the deleted tab. However, the span value remained correct. It's quite strange - could this be a bug? Check ou ...

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 ...

angular2 variable turns null during post request, synchronization breakdown

Currently, I am in the process of developing an ecommerce web application using Angular2 and have encountered a issue with saving ordered information in session. addToCart(productId:string,noOfItems:number):void{ let itemCounts; let selectedItems= ...

Replicating an array of typed objects in Angular2

I have a collection of specific object types and I'm looking to duplicate it so that I can work on a separate version. In order for the configuratorProduct to function correctly, I need to provide it with a copy of the listProducts values: listPro ...

What is the process for choosing nested colors from a theme in Material UI?

I have a question regarding how to select a nested style from my theme when creating a Button. Below is the snippet of code that illustrates my dilemma: const buttonStyle: SxProps<Theme> = { '&:hover': { backgroundColor: 'bac ...

Tips for implementing a reusable instance of a class in (SSR) React (comparable to a @Bean in Spring)

I am currently developing a new application using Next.js and React (Server Components) in TypeScript. In order to showcase and evaluate the app, I need to support two different data sources that provide identical data through separate APIs. My goal is to ...

Tips for circumventing debounceTime in Angular

In my current setup, I am utilizing a text input along with a debounceTime pipe to ensure that server requests are not made too frequently while the user is typing: this.keyUp$ .pipe(debounceTime(500)) .subscribe(data => this.onInputChanged.emit ...

Issues arise when attempting to store data into an array with the assistance of FileReader

I am currently working on an Angular4 project where I am facing an issue with saving Blob data returned from my API call to an array of pictures in base64 format. This is so that I can later display the images using *ngFor. Here is the API call I am makin ...

Concealing the BottomNavigation bar in Nativescript

Currently using Nativescript 7+ and seeking to implement a feature where the TabStrip can be hidden on certain pages post navigation. Below is the relevant section of my .html code. <BottomNavigation id="bottomNav"> <TabStrip> ...