角度2-等效于根范围? [英] Angular 2 - What is equivalent to Root Scope?

查看:83
本文介绍了角度2-等效于根范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部!我有这个组件,当我单击href时,应该将变量设置为Root Scope(如果它是Angular 1),如下所示:

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?

推荐答案

要实现全局变量,可以实现共享服务.您将能够保存数据,并且所有组件都可以访问它们.

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 ]);

请注意不要在要使用它的组件的providers属性中再次定义它.

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

样品

服务:

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

将其用作组件:

@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:

angular.io网站上的此页面也可能使您感兴趣:

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

这篇关于角度2-等效于根范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆