Search code examples
angulartypescriptangular2-templateangular2-services

Binding Component's variable to service


I need to take a reference of a variable that is in a service. The variable in the service also can be changed by another function that is in another component. It is hard to explain so let me show you.

SharedService;

@Injectable()
export class SharedService {

    sharedpages = {
        items: [
                {id: "1", link: "", text: "Epiaş", parent: "0", active: false, tabbed: false},
                {id: "T001", link: "T001", text: "T001 | Abone Bul", parent: "1", active: false, tabbed: false},
               ],
            getAll:  () => {
                return this.sharedpages.items;
            }
        };
    }

AppComponent;

export class AppComponent {
  public pages;

  constructor(public SharedService: SharedService) {
// The code below just takes sharedpages from sharedservice once then it doesn't takes updates of the sharedpages.
        this.pages = SharedService.sharedpages.getAll();

//The code below also doesn't work
        this.pages = SharedService.sharedpages.items;
      }
    }

I want to update pages variable from AppComponent whenever sharedpages from SharedService changes.

for example some other function from another component changed sharedpages.items to blank array. When this happen I want to make pages variable from Appcomponent to blank array too.

Are there any solution for this? Thank you...


Solution

  • Try this:

    @Injectable()
    export class SharedService {
    
    public pagesChanged$: ReplaySubject<any> = new ReplaySubject<any>(1);
    sharedpages = {
        items: [
                {id: "1", link: "", text: "Epiaş", parent: "0", active: false, tabbed: false},
                {id: "T001", link: "T001", text: "T001 | Abone Bul", parent: "1", active: false, tabbed: false},
               ],
            getAll:  () => {
                return this.sharedpages.items;
            }
        };
    }
    

    AppComponent;

    export class AppComponent implements OnInit {
     public pages;
    
     constructor(public sharedService: SharedService) {}
    
    ngOnInit() {
        this.sharedService.pagesChanged$.subscribe(data => {
            this.pages = data;
        });
    }
    
    }
    

    And in your component on which the pages getting changed, emit new value

    export class AnotherComponent {
    
     constructor(public sharedService: SharedService) {}
    
    onPageChange() {
        this.sharedService.pagesChanged$.next(null); // Emits null as new value
    }
    
    }
    

    Added a working example https://ng-run.com/edit/1zZGSvohchUeEG8dacXt?open=app%2Fanother.component.ts&layout=2