0

I'm using a service to share data between two unrelated controllers as mentioned in this article

https://www.infragistics.com/community/blogs/b/infragistics/posts/simplest-way-to-share-data-between-two-unrelated-components-in-angular

This is the service which i use to share the data

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

@Injectable({
  providedIn: 'root'
})
export class AppService {
  tempfile = "temp";

  file: BehaviorSubject<string>;
  count: BehaviorSubject<number>;
  constructor() {

    this.file = new BehaviorSubject(this.tempfile);
  }

 
}

I injected this service to my component,but when i try to get the value from the service

this.appsevice.file.subscribe(c => {
        this.file = c;
      });

i keep getting the following error

this.appsevice.file.subscribe is not a function

techno
  • 6,100
  • 16
  • 86
  • 192
  • In the component that is consuming the shared service, have you imported the component and added it to the Constructor? constructor(private appsevice: AppService) { } – DanielG Jun 25 '20 at 12:43
  • 1
    Also, this may have a typo: this.appsevice.file.subscribe (missing r, or maybe should be this.appService, depending on how you declared it) – DanielG Jun 25 '20 at 12:46
  • @DanielG Yes, i have imported and injected it.The typo is not an issue,its declared wrong. – techno Jun 25 '20 at 13:50
  • In your service, try returning an observable: currentFile = this.tempFile.asObservable();, and then in your component, fetch it like this: this.appsevice.currentFile .subscribe(c => { this.file = c; });. An example is here: https://stackoverflow.com/questions/37587732/how-to-call-another-components-function-in-angular2 (unrelated components section) – DanielG Jun 25 '20 at 14:02
  • 1
    @DanielG I simply used this approach https://www.c-sharpcorner.com/article/angular-services-for-sharing-data-between-component-using-angular-and-above/ and it workds. – techno Jun 25 '20 at 14:04
  • `file: BehaviorSubject=new BehaviorSubject()` You forget give value to "file" -you only say to Angular the type, but it's undefined until you give a value – Eliseo Jun 25 '20 at 16:29

0 Answers0