Angular 2-使用共享服务 [英] Angular 2 - Using Shared Service

查看:86
本文介绍了Angular 2-使用共享服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来像共享服务是解决许多情况的最佳实践,例如组件之间的通信或替换angular 1的旧$ rootscope概念.我正在尝试创建我的我的产品,但它没有用.有什么帮助吗? ty !!!

Looks like shared services is the best practice to solve many situations such as communication among components or as replacement of the old $rootscope concept of angular 1. I'm trying to create mine, but it's not working. Any help ? ty !!!

app.component.ts

app.component.ts

import {Component} from 'angular2/core';
import {OtherComponent} from './other.component';
import {SharedService} from './services/shared.service';
@Component({
selector: 'my-app',
providers: [SharedService],
directives: [OtherComponent],
template: `
    <button (click)="setSharedValue()">Add value to Shared Service</button>
    <br><br>
    <other></other>
`
})
export class AppComponent { 
data: string = 'Testing data';
setSharedValue(){
    this._sharedService.insertData(this.data);
    this.data = '';
    console.log('Data sent');
}
constructor(private _sharedService: SharedService){}
}

other.component.ts

other.component.ts

import {Component, OnInit} from "angular2/core";
import {SharedService} from './services/shared.service';
@Component({
selector : "other",
providers : [SharedService],
template : `
I'm the other component. The shared data is: {{data}}
`,
})
export class OtherComponent implements OnInit{
data: string[] = [];
constructor(private _sharedService: SharedService){}
ngOnInit():any {
    this.data = this._sharedService.dataArray;
}
}

推荐答案

大多数时候,您需要在引导应用程序时定义共享服务:

Most of time, you need to define your shared service when bootstrapping your application:

bootstrap(AppComponent, [ SharedService ]);

,并且不会在组件的providers属性中再次定义它.这样,您将在整个应用程序中拥有一个服务实例.

and not defining it again within the providers attribute of your components. This way you will have a single instance of the service for the whole application.

在您的情况下,由于OtherComponentAppComponent的子组件,因此只需删除providers属性,如下所示:

In your case, since OtherComponent is a sub component of your AppComponent one, simply remove the providers attribute like this:

@Component({
  selector : "other",
  // providers : [SharedService], <----
  template : `
    I'm the other component. The shared data is: {{data}}
  `,
})
export class OtherComponent implements OnInit{
  (...)
}

这样,他们将为两个组件共享相同的服务实例. OtherComponent将使用父组件(AppComponent)中的一个.

This way they will shared the same instance of the service for both components. OtherComponent will use the one from the parent component (AppComponent).

这是因为Angular2具有分层注入器"功能.有关更多详细信息,请参见以下问题:

This is because of the "hierarchical injectors" feature of Angular2. For more details, see this question:

这篇关于Angular 2-使用共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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