I'm using Subject & Subscription to transfer data between two components but it's not working for me.
// First Component
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { SettingsHelperService } from '../settings-screen/settings-helper.service';
@Component({
selector: 'app-master-data-config',
templateUrl: './master-data-config.component.html',
styleUrls: ['./master-data-config.component.css']
})
export class MasterDataConfigComponent implements OnInit, OnDestroy {
zoneSelected: boolean = false;
wingSelected: boolean = false;
public subscription: Subscription;
constructor(private settingHelperService: SettingsHelperService) { }
public ngOnDestroy(): void {
this.subscription.unsubscribe(); // onDestroy cancels the subscribe request
}
ngOnInit(): void {
this.subscription = this.settingHelperService.getSelectedValue().subscribe(data => console.log(data));
}
}
// Second Component
import { Component, OnInit } from '@angular/core';
import { SettingsHelperService } from './settings-helper.service';
@Component({
selector: 'app-settings-screen',
templateUrl: './settings-screen.component.html',
styleUrls: ['./settings-screen.component.css']
})
export class SettingsScreenComponent implements OnInit {
public UnitType = [
{value: 'matric', viewValue: 'Matric'},
{value: 'imperial', viewValue: 'Imperial'},
];
zoneSelect: boolean = false;
wingSelect: boolean = false;
selectedUnitType: string;
valueSelected = [];
constructor(private settingHelperService: SettingsHelperService) { }
ngOnInit() {
}
save(){
let valueObj = {
unitType: this.selectedUnitType,
zoneSelect: this.zoneSelect,
wingSelect: this.wingSelect
}
this.settingHelperService.setValues(valueObj);
}
}
// Service
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
@Injectable()
export class SettingsHelperService {
public unitType:string;
public valueSubmitted = null;
public data = new Subject<any>();
constructor() { }
getSelectedValue(){
return this.data.asObservable();
}
setValues(value){
console.log(value);
this.data.next(value);
}
}
Please suggest where am I wrong..?
I'm not retrieving the updates values in component.
I don't see any obvious problems with your code except that you didn't show the code where you provide the SettingHelperService. That could be an issue. If not correctly provided both components could have their own instance of the service and not sharing the same one. Try adding this code in the service:
@Injectable({
providedIn: 'root',
})
If that doesn't help then check this Stackblitz I made based on your code. After adding the above it works as it is: https://angular-ivy-g8keel.stackblitz.io