import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BehavService {
private data = new BehaviorSubject('');
currentData = this.data.asObservable();
constructor() { }
setData(data:any) {
this.data.next(data);
}
}
==== Komponens 1 ====
import { Component, OnInit } from '@angular/core';
import { BehavService } from '../behav.service';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.scss']
})
export class Comp1Component implements OnInit {
data: any = 'alma';
constructor(private behav: BehavService) { }
ngOnInit(): void {
}
sendDataToService() {
this.behav.setData(this.data)
}
}
comp1 works!
{{data}}
==== Komponens 2 ====
import { Component, OnInit } from '@angular/core';
import { BehavService } from '../behav.service';
@Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.scss']
})
export class Comp2Component implements OnInit {
data: any;
constructor(private behav: BehavService) { }
ngOnInit(): void {
this.behav.currentData.subscribe(data => {
this.data = data;
})
}
}
comp2 works!
{{data}}