Error: The method "next" cannot be used with BehaviorSubject

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';

Answer №1

Within the template of ServersSelectComponent, there is the following code:

[(ngModel)]="this.dashboardService.selectedServer"

This line will replace the value of the selectedServer service property with one of the available options.

If you wish to notify changes using a RxJS Subject, it is recommended to avoid using [(ngModel)] and instead manually trigger the change using an event listener like (change) such as (change)="change($event)".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with a void method in a React unit test by treating it as an object's property

How can I pass a value to a function in an interface to trigger a click event on an element? I have a React component that I want to write unit tests for: const VariantItem = (props: VariantItem): ReactElement => { return ( <div key={props.produc ...

Utilizing Angular's Mat-Table feature to dynamically generate columns and populate data in a horizontal manner

I am in need of a solution where I must populate the mat-table in a horizontal format with an array of JSON objects. The input array is as follows: [{ "SAMPLERULEID": 69, "SAMPLERULENAME": "Sample1", &q ...

Implement a personalized click function for the delete icon in the mini cart

Is there a way to customize the click event for the remove button in the mini cart? function ajax_call(){ $.ajax({ url: ajax_url, type: 'post', data: {action : 'remove_from_cart','cart_item_key' : 10}, ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

The Colorful World of CSS Backgrounds

I've been searching for hours trying to track down the source of this strange greenish background color. I've combed through every single file and it's starting to drive me insane. Any ideas where this color could be coming from? I highly d ...

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

Incorporate a fresh button into the Tinymce toolbar using C# programming

I have utilized Tinymce text editor/textarea in my webpage. How can I incorporate an additional button onto the toolbar? For instance, upon clicking the added button, it should prompt a dialog with three textfields: title, age, and gender. Upon filling ou ...

Is there a way for me to generate a preview thumbnail for my video?

Looking to add a preview effect to video thumbnails when users hover over them, displaying a series of frames from the video. Are there any jQuery plugins or tutorials available for creating this effect? ...

Confirm before closing the window

How can I get this code to function properly and show a confirmation alert after the user clicks on a button? This is essentially an "exit website button". The confirmation pop-up will have: If "OK" is clicked > the current window will close; If ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

Ways to display an icon upon hovering or clicking, then conceal it when the mouse is moved away or another list item is clicked using ngFor in Angular 7

Within a simple loop, I have created a list with multiple rows. When a row is clicked or hovered over, it becomes active. Subsequently, clicking on another row will deactivate the previous one and activate the new one. So far, everything is functioning c ...

Exploring the possibility of integrating direct search functionality into the URL bar within an Angular application

One interesting feature I observed on GitHub is that after typing "github.com" in the URL bar, you can directly search by pressing the spacebar, which activates the "search mode." Here's how it looks like on Chrome: https://i.sstatic.net/XIgJu.png I ...

The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled. In the second scenario, when the user clicks ...

Submitting data via AJAX using the method parameter

I have a specific ajax form that requires serialization and the manual setting of the _method for the data form. This is how I am currently handling it. $.ajax({ url: http://someposturl.com/object, type: 'POST', ...

What is the method for transmitting a message from localhost to a React frontend?

I am currently running a WebSocket server that is receiving streams of messages from an MQTT source. These messages are then sent to a localhost server on port 8080. The messages being received are actually a stream of random numbers. Below is the Python ...

Crafting a Retro Style

I have an interface called Product which includes properties such as name, and I want to track changes to these products using a separate interface called Change. A Change should include the original Product as well as all of its properties prefixed with t ...

Leveraging Angular 2 Service with the Power of RxJS BehaviorSubject or EventEmitter

Being new to Angular 2 and RXJS, I find myself faced with a challenge involving a custom header component that has 2 triggers (buttons) meant to activate 2 distinct navigation directives in different areas of the application. To address this issue, I have ...

Ways to convert asynchronous operations of Node.js into synchronous operations in Node.js

Using node js, I am making multiple AWS API calls within a for loop. var prodAdvOptions = { host : "webservices.amazon.in", region : "IN", version : "2013-08-01", path : "/onca/xml" }; prodAdv = aws.createProdAdvCli ...

Navigate to the top of the page using Vue Router when moving to a new

Currently, in my Vue application, whenever I click on a <router-link>, it directs me to the new page but at the same scroll position as the previous one. This happens because the link only replaces the component. I am curious to know if there is a s ...