角度2 – 相当于根范围?
发布时间:2020-12-17 08:19:34 所属栏目:安全 来源:网络整理
导读:所有!我有这个组件,当我点击href,它应该设置一个变量作为根范围,如果它是Angular 1像这样: selector: 'my-component'template : ` div (click)="addTag(1,'abc')"`constructor() { this.addTag = function(id,desc){ myGlobalVar = { a: id,b: desc}; }
所有!我有这个组件,当我点击href,它应该设置一个变量作为根范围,如果它是Angular 1像这样:
selector: 'my-component' template : ` <div (click)="addTag(1,'abc')">` constructor() { this.addTag = function(id,desc){ myGlobalVar = { a: id,b: desc}; }; 然后在我的父组件中,页面本身(实际上)我应该做的事情就像: <my-component></my-component> <p>My Component is returning me {{ ?????? }} 做这样的事情最好的办法是什么?
要实现全局变量,可以实现共享服务。您将能够保存数据,所有组件都可以访问它们。
为此,只需执行一个服务并设置其提供程序,当您的应用程序: bootstrap(AppComponent,[ MySharedService ]); 小心不要在要使用组件的providers属性中再次定义它。 样品 服务: 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' }); } } 如果要通知组件数据更新,您可以将可观察字段用于共享服务: @Component({ (...) }) export class MyComponent { constructor(private service:MySharedService) { this.service.dataChange.subscribe((data) => { this.data = data; }); } } 有关详细信息,请参阅此问题: > Delegation: EventEmitter or Observable in Angular2 在angular.io网站上的这个页面也可能引起你的兴趣: > https://angular.io/docs/ts/latest/cookbook/component-communication.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |