Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Angular 2 - Using Shared Service

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

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

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;
}
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

bootstrap(AppComponent, [ SharedService ]);

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.


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{
  (...)
}

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...