im developing an admin panel where the admin can see all the bookings that have been requested and select those who he will accept; and I want to display those 'accepted' bookings in a different tab (different component, in a different route). Im using a SharedService with a BehaviorSubject but it doesnt work: All I get in the 2nd component is an anonymousSubject array, which is empty. Im not showing the first component which sends the booking to the service cause thats working fine. Help please!
shared Service
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {Turno} from '../models/turno';
@Injectable({
providedIn: 'root',
})
export class SharedService{
private acceptedBookings=[];
public acceptedBookingsSubject= new BehaviorSubject<Turno[]>([]);
//public turno:Turno;
constructor(){
}
addToAccepted(turno : Turno){
this.acceptedBookings.push(turno);
this.acceptedBookingsSubject.next(this.acceptedBookings);
console.log(this.acceptedBookingsSubject);
}
}
and here is the second component.
Second component, which consumes the service and has to display the array.
import { Component, OnInit} from '@angular/core';
import {SharedService} from '../../services/shared.service';
import {Observable} from 'rxjs';
import {Turno} from '../../models/turno';
import {share} from 'rxjs/operators';
@Component({
selector: 'app-turnoaceptado',
templateUrl: './turnoaceptado.component.html',
styleUrls: ['./turnoaceptado.component.css'],
providers:[SharedService]
})
export class TurnoaceptadoComponent implements OnInit {
public acceptedBookings:Observable<Turno[]>;
ngOnInit(): void {
}
constructor(private _sharedService: SharedService) {
this._sharedService.acceptedBookingsSubject.pipe(share());
}
}
And in the html of the 2nd component im using the async pipe |
At ngOnInit, just add:
this.acceptedBookings = this._sharedService.acceptedBookingsSubject.asObservable();
Then you can choose if you prefer to create a subscription on it or use pipe async.
Additional tip, once you set the SharedService with { providedIn: 'root' }
, you don't need to put the SharedService on any providers array.
I have created a demo: stackblitz