简体   繁体   中英

how to do data sharing of service among two different components in Angular 2

I am in learning mode of Angular 2 . I am implementing the singleton service in angular just to know how does it work. this is my service class

import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
    constructor() {
        console.log("new instance");
    }
    dataValue: string = "i am singleton";
}

Here it is my Two components where i am using this service first one

import { Component } from '@angular/core';
import { DataService } from './dataservice';

@Component({
    selector: 'first',
    template: `
                 <div>
                        Your Input : <input type = "text" [(ngModel)] = "ChangeByFirstComponent">
                        You Entered : {{ChangeByFirstComponent}}
                 </div>   
                `
})

export class FirstComponent {
    constructor(private _dataService: DataService) { }
    ChangeByFirstComponent: string;

    get DataValue(): string {
        return this._dataService.dataValue;
    }

    set DataValue(ChangeByFirstComponent)
        {
            this._dataService.dataValue = this.ChangeByFirstComponent;
        }
}
second one 
import { Component } from '@angular/core';
import { DataService } from './dataservice';

@Component({
    selector: 'second',
    template: `
                 <div>
                        Your Input : <input type = "text" [(ngModel)] = "ChangeBySecondComponent">
                        You Entered : {{ChangeBySecondComponent}}
                 </div>  ` 

})

export class SecondComponent {
    constructor(private _dataService: DataService) { }
    ChangeBySecondComponent: string;

    get DataValue(): string {
        return this._dataService.dataValue;
    }

    set DataValue(ChangeByFirstComponent) {
        this._dataService.dataValue = this.ChangeBySecondComponent;
    }
}

I provided the providers in root module for single instance hence and it is working fine as i checked it throw developer tool. I am implementing that if the user change the value from firstcomponent so it should change on secondcomponent to (this is what singleton provided us , makes data sharing easily) . I am not getting my output . what is the problem ?

您可以使用BehaviorSubject做到这一点,更多的BehaviorSubject 这里我已经给了答案,类似的问题在这里

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM