Angular 2 - What is equivalent to Root Scope?

后端 未结 3 1479
攒了一身酷
攒了一身酷 2020-11-29 00:07

All! I\'ve this component where when I click on the href it is supposed to set a variable as Root Scope if it was Angular 1 like this:

selector: \'my-compone         


        
3条回答
  •  臣服心动
    2020-11-29 01:00

    To implement global variable, you could implement a shared service. You will be able to save data it and all components could have access to them.

    For this, simply implement a service and set its provider when boostrapping your application:

    bootstrap(AppComponent, [ MySharedService ]);
    

    Be careful not to define it again within the providers attribute of components where you want to use it.

    Sample

    The service:

    export class MySharedService {
      data: any;
      dataChange: Observable;
    
      constructor() {
        this.dataChange = new Observable((observer:Observer) {
          this.dataChangeObserver = observer;
        });
      }
    
      setData(data:any) {
        this.data = data;
        this.dataChangeObserver.next(this.data);
      }
    }
    

    Use it into a component:

    @Component({
      (...)
    })
    export class MyComponent {
      constructor(private service:MySharedService) {
      }
    
      setData() {
        this.service.setData({ attr: 'some value' });
      }
    }
    

    If you want to notify components that the data were updated you can leverage observable fields into the shared service:

    @Component({
      (...)
    })
    export class MyComponent {
      constructor(private service:MySharedService) {
        this.service.dataChange.subscribe((data) => {
          this.data = data;
        });
      }
    }
    

    See this question for more details:

    • Delegation: EventEmitter or Observable in Angular2

    This page on the angular.io website could also interest you:

    • https://angular.io/docs/ts/latest/cookbook/component-communication.html

提交回复
热议问题