0

I am trying to pass a variable from one component to another. I am doing that by using a service:

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


    @Injectable()
    export class SharedService {
      // private questionNumber = new Subject<number>();
      // questionNumber$ = this.questionNumber.asObservable();
      questionNumber : number;
      publishData(number:number) {
        this.questionNumber = number;
        console.log(this.questionNumber,'publish');
      }

  getQuestionData(){
    console.log(this.questionNumber,'get');
    return this.questionNumber;
  }

  constructor() { }

}

If the data gets changed in the function "publishData" it writes the current variable value in the console:

publish Variable

But if I try to access that variable it is still undefined as if it isn't changed

Undefined get

Component 1 (excerpt) :

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { SharedService } from '../shared.service';

@Component({
  selector: 'app-main-quiz',
  templateUrl: './main-quiz.component.html',
  styleUrls: ['./main-quiz.component.css'],
  encapsulation: ViewEncapsulation.None,
  providers: [SharedService]
})
export class MainQuizComponent implements OnInit {

  constructor(private _sharedService: SharedService){
    this._sharedService = _sharedService;
  }

  updateQuestion(){
    this._sharedService.publishData(this.questionNumber);
  };

Component 2:

import { Component, OnInit, Input } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { SharedService } from '../shared.service';

@Component({
  selector: 'app-win-page',
  templateUrl: './win-page.component.html',
  styleUrls: ['./win-page.component.css'],
  encapsulation: ViewEncapsulation.None,
  inputs: ['questionNumber'],
  providers: [SharedService]
})
export class WinPageComponent implements OnInit {

  constructor(private _sharedService : SharedService) {
    this._sharedService = _sharedService;
    this.questionNumber = this._sharedService.getQuestionData();
   }

  questionNumber : number;

  ngOnInit() {

  }

  ngOnChanges(){
    this.questionNumber = this._sharedService.getQuestionData();
  }

}

Why isn't that variable updated ?

Thanks for your help!

Snixells
  • 121
  • 2
  • 11

1 Answers1

2

As already answered here: Angular - shared service between components doesn't work

Each component has :

providers: [SharedService]

So based on the angular DI Hierachy the service will be available only for the current component. In your case that mean each components will have his own instance (service isolation).

If you want your component to share the same instance you need to declare the provider at the module level.

eko
  • 39,722
  • 10
  • 72
  • 98
JEY
  • 6,973
  • 1
  • 36
  • 51