Angular 2 - What is equivalent to Root Scope?

后端 未结 3 1481
攒了一身酷
攒了一身酷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:04

    You can implement this by using angular BehaviorSubject and asObservable

    Check below example code

    Service file

    @Injectable()
    export class commonService {
        private data = new BehaviorSubject('');
        currentData = this.data.asObservable()
    
        constructor() { }
    
        updateMessage(item: any) {
            this.data.next(item);
        }
    
    }
    

    Component 1

    Set the data from any component

     constructor(private _data: commonService) { }
     shareData() {
          this.currentValue = this.queryTerm;
          this._data.updateMessage(this.currentValue);
      }
    

    Listen from any component

    constructor(private _data: commonService) { }
    ngOnInit() {
            this._data.currentData.subscribe(currentData => this.currentValue = currentData)
        }
    

    You can communicate between any component using this way.

    More Info and other 7 methods

提交回复
热议问题