Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

Angular 2 - What is equivalent to Root Scope?

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-component'
template : `
            <div (click)="addTag(1, 'abc')">`

constructor() {
    this.addTag = function(id, desc){
        myGlobalVar = { a: id, b: desc};
    };

Then in my parent component, the page itself (in fact) I should be doing something like:

<my-component></my-component>
<p>My Component is returning me {{ ?????? }}

What is the best approach to do such a thing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  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:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...