Jebathon
Jebathon

Reputation: 4561

Angular 6 - unable to subscribe to data returned from a service

I am trying to build a simple cache service in Angular; a service with a simple setter/getter function that different components can fetch data from.

Unfortunately when subscribing to this service to get the data, the subscribe callback is never called and the data is not retrieved.

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;
    });
  }
...

I have injected the service in the module class and there are no compilation errors. The data in the component is just never set.

Upvotes: 2

Views: 2496

Answers (2)

Jameel Moideen
Jameel Moideen

Reputation: 7931

You can do something like below

   export class CacheService {

     //create 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;
    }

On your component you can subscribe like below.

service.getCacheData().susbcribe((data)=>{
    //here you will get
});

You can also check the below answer how's observable working

How create observable with parameters in Angular 6?

Upvotes: 1

Yoarthur
Yoarthur

Reputation: 917

You need to provide data in cacheData.

use this an example.

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)
      }
    )
  }
}

in there, you create a new Observable from ngrx library, which comes with angular.

And then set values you gonna consume (with observer.next()) once you subscribe to cacheData property.

observer.next() can receive as arguments.

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

For a more closer look, https://angular-2-training-book.rangle.io/handout/observables/.

Upvotes: 1

Related Questions