将组件的变量绑定到服务

Binding Component's variable to service

我需要引用服务中的变量。服务中的变量也可以被另一个组件中的另一个函数更改。很难解释,让我告诉你。

共享服务;

@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;
            }
        };
    }

应用组件;

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

我想在 SharedService 的共享页面发生变化时更新 AppComponent 的页面变量。

例如,另一个组件中的一些其他函数已将 sharedpages.items 更改为空白数组。发生这种情况时,我也想使页面变量从 Appcomponent 变为空白数组。

有什么解决办法吗?谢谢...

您需要在服务上导入注入

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

@Injectable()
export class SharedService {

并导入您的组件

import { SharedService } from './SharedService ';
export class AppComponent {
   console.log(SharedService.sharedpages);

你可以选择 Observables/Subscription。在更新任何组件中的服务变量时,说

updateSharedPages() { // your logic to update goes here }

调用触发更改的方法。这是使用 BehaviorSubjectSubject 完成的,具体取决于您的用例。让我们取一个变量(在您的服务中)

updateSharedModelSubject = new Behavior subject<boolean>(true);

然后

triggerSharedModelChange() { this.updateSharedModelSubject.next(this.sharedpages); }

然后您可以在任何组件的任何地方订阅它。

试试这个:

@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;
        }
    };
}

应用组件;

export class AppComponent implements OnInit {
 public pages;

 constructor(public sharedService: SharedService) {}

ngOnInit() {
    this.sharedService.pagesChanged$.subscribe(data => {
        this.pages = data;
    });
}

}

然后在页面发生变化的组件中发出新值

export class AnotherComponent {

 constructor(public sharedService: SharedService) {}

onPageChange() {
    this.sharedService.pagesChanged$.next(null); // Emits null as new value
}

}

添加了一个工作示例 https://ng-run.com/edit/1zZGSvohchUeEG8dacXt?open=app%2Fanother.component.ts&layout=2