0

example.service.ts

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

@Injectable()
export class ExampleService {

    number1 : number;
    number2 : number;
    result : number;
    constructor() { }

}

component1.component.ts

import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'

@Component({
    selector: 'app-component1',
    templateUrl: './component1.component.html',
    styleUrls: ['./component1.component.css'],
    providers: [ExampleService]
})
export class Component1Component implements OnInit {

    number1v = null;
    number2v = null;
    resultv = null;

    constructor(public aService : ExampleService ) { 
        this.aService.number1 = this.number1v;
        this.aService.number2 = this.number2v;
        this.aService.result = this.resultv;
    }
    ngOnInit() {
    }
    processForm(){
    this.resultv = this.number1v + this.number2v;
    }
}

component2.component.ts

import { Component, OnInit } from '@angular/core';
import { ExampleService } from '../example.service'

@Component({
    selector: 'app-component2',
    templateUrl: './component2.component.html',
    styleUrls: ['./component2.component.css'],
    providers: [ExampleService]
})
export class Component2Component implements OnInit {
    resultv;
    constructor(public aService : ExampleService) { 
        this.aService.result = this.resultv;
    }

    ngOnInit() {
    }
    getResult(){
        alert(this.resultv)
    }
}

Want to pass a value of result from component1 to component2.

No parent to child or child to parent component.

the result i get is undefined.

Vamshi
  • 9,194
  • 4
  • 38
  • 54
Om Patel
  • 227
  • 1
  • 3
  • 9
  • Use this [**blog post**](https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/) – Aravind Jul 07 '17 at 10:42
  • 1
    Possible duplicate of [Angular - shared service between components doesn't work](https://stackoverflow.com/questions/43997489/angular-shared-service-between-components-doesnt-work) – eko Jul 07 '17 at 10:52

1 Answers1

0

The problem, is when component A updates the service, component B is not aware of the changes. So, to solve this we need to use Observer pattern and let all observers be informed of the change.

Luckily Angular comes with rxjs, so we can use BehaviorSubject to implement the observer pattern.

Service Code

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

@Injectable()
export class ExampleService {

    number1 = new BehaviorSubject<number>(0);
    number2 = new BehaviorSubject<number>(0);
    result = new BehaviorSubject<number>(0);
    constructor() { }

}

Inside component you can read their values

service.number1.subscribe(num => {
   // ....
});

To change any number you can just update it this way

service.number1.next(1); // set new number 

Ofcourse this is crude way, you can get better examples reading online tutorials or answers on BehaaviorSubject

Vamshi
  • 9,194
  • 4
  • 38
  • 54