I am trying to better understand services with a very simple application that receives and updates the value of a string inside a service and displays it in a component.
Here's the service:
import {Injectable} from 'angular2/core'; @Injectable() export class SharedService { dataString: string; insertData(data) { this.dataString = data } }
Here's the main "application":
import {Component} from 'angular2/core'; import {OtherComponent} from './other'; import {SharedService} from'./shared.service'; @Component({ selector: 'my-app', providers: [SharedService], directives: [OtherComponent], template: ` <input type="text" #someValue> <button (click)="setSharedValue(someValue.value)">Change value in shared service</button> <br><br> <other></other> ` }) export class AppComponent { constructor(private _sharedService: SharedService){} setSharedValue(value){ this._sharedService.insertData(value); } }
... and here is the "other" component:
import {Component, OnInit} from 'angular2/core'; import {SharedService} from './shared.service'; @Component({ selector : "other", template : ` I'm the other component. The shared data is: <p>{{data}}</p> `, }) export class OtherComponent implements OnInit{ data: string; constructor(private _sharedService: SharedService){} ngOnInit() { this.data = this._sharedService.dataString; } }
Here is the plunkr.
When the text is added to the input and the button is pressed, I want to display the value entered in the "other" component to demonstrate the receipt and configuration of service data. However, he just fails.
Can someone explain what I'm doing wrong?
thanks
angular angular2-services
Dan
source share