My goal is to share data between sibling components by utilizing a shared service. The first component loads and retrieves a list of Servers from the API, populating a select box with all the servers. I now need to notify the other component when the user selects a new server in order to display its details.
Here's my service:
@Injectable()
export class DashboardService {
servers: Server[] = [];
selectedServer = new BehaviorSubject<Server>(null);
setServers(servers: Server[]) {
this.servers = servers;
}
}
Component containing the select box:
@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));
}
// todo: pass to dashboard component
public change = (event: any) => {
console.log(event);
this.dashboardService.selectedServer.next(event);
}
}
Detail 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;
});
}
}
Although the change() method is triggered correctly upon selecting a new server, an error is thrown in the console:
ERROR TypeError: _this.dashboardService.selectedServer.next is not a function at ServersSelectComponent.change (servers-select.component.ts:39)
The subscription appears to be functioning as expected since 'nulllalalal' is logged in the console. What am I overlooking?
EDIT: - My setup involves Angular 5 and rxjs 5.5.2 - In my DashboardService, I import BehaviorSubject like so:
import { BehaviorSubject } from 'rxjs/BehaviorSubject';