I am trying to share data between sibling components and do this through a shared service. When the first component loads, it retrieves the server list from my API and populates the selection box with all the retrieved servers. Now I want to notify my other component when the user has selected a new server so that I can display its details.
This is my service:
@Injectable() export class DashboardService { servers: Server[] = []; selectedServer = new BehaviorSubject<Server>(null); setServers(servers: Server[]) { this.servers = servers; } }
Component with selection field:
@Component({ selector: 'app-servers-select', template: ` <div class="form-group"> <label>Server</label> <select class="form-control" [(ngModel)]="this.dashboardService.selectedServer" (ngModelChange)="change($event)"> <option disabled>-- Select server --</option> <option *ngFor="let server of servers" [ngValue]="server">{{server.Name}}</option> </select> </div>`, styleUrls: ['./servers-select.component.css'], providers: [ServerService] }) export class ServersSelectComponent implements OnInit { servers: Server[] = []; constructor(private serverService: ServerService, private dashboardService: DashboardService) { } ngOnInit() { this.serverService .getServers() .subscribe(s => { this.servers = s; this.dashboardService.setServers(s); console.log(s); }, e => console.log(e)); }
Detailed component:
@Component({ selector: 'app-server-details', template: ` <section> <div class="form-group"> <label>Description</label> <input type="text" [(ngModel)]="server"> </div> </section> `, styleUrls: ['./server-details.component.css'] }) export class ServerDetailsComponent implements OnInit { private server: Server = null; constructor(private dashboardService: DashboardService) { } ngOnInit() { this.dashboardService.selectedServer.subscribe((value: Server) => { console.log(value + 'lalalal'); this.server = value; }); } }
When I select a new Server, the change () method is called correctly, but the following error appears on the console:
ERROR TypeError: _this.dashboardService.selectedServer.next is not a function on the ServerSelectComponent.change server (servers-select.component.ts: 39)
Subscriptions seem to work already since I get "nulllalalal" in my console. What am I missing?
EDIT: - I am using angular 5 and rxjs 5.5.2 - In my DashboardService I import BehaviorSubject as follows:
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
source share