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:
But if I try to access that variable it is still undefined as if it isn't changed
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!