Uncertain about the best way to utilize an observable

I am currently developing a real-time chat application using Angular and Node.js. The backend is powered by nodejs and I am utilizing socket.io for communication.

Server Side

 io.on('connection', (socket) => {
  socket.on('new-message', (message) => {
    io.emit(message);

  });
}); 

Client Side

Service

private url = 'http://localhost:3000';
  private socket;
constructor( private httpClient: HttpClient ) {
    this.socket = io(this.url);
}
 public sendMessage(message:Message){
    this.socket.emit('new-message',message);
  }
 public getMessages = () => {
    return new  Observable(observer => {
        this.socket.on('new-message', (message) => {
            observer.next(message);

        });
    });
}

Component

messages:any[]=[];
constructor(private chatService:ChatService){}
ngOnInit(): void {
  this.chatService.getMessages()
  .subscribe((message:any)=>{
    this.messages.push(message);

  })
onSubmit(){
//extracting message from the input form (not relevant i think i can add it if suggested)
this.chatService.sendMessage(tosend);
}

component.html

<div *ngFor="let m of messages">
 {{m.text}}
</div>
<! -- a form to send messages  -->

Answer №1

It seems that the problem was on the server side and I had to modify
io.emit(message); to io.emit('new-message', message)

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

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

In the callback function within Array.prototype.map, make sure to access the newly created array

Array.prototype.map() creates a new array. How can I use this new array within the callback function passed to Array.prototype.map()? For instance: someArray.map(function(item, idx, arr) { return { theCreatedArray: xyz }; }); What should I assign to ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Struggling to assign the correct data type to a property in Typescript

I am encountering a TypeScript error with the following code. In this interface, the 'items' property can be either an object or an array depending on the code and response. I am unsure how to specify the datatype of 'array/object/any', ...

Can each `InstancedBufferGeometry` instance have its own set of unique vertex colors?

Is it possible to assign different vertex colors to each instance of InstancedBufferGeometry? const xRes = 3; const yRes = 2; const numVertices = xRes * yRes; geometry = new THREE.InstancedBufferGeometry(); geometry.copy(new THREE.PlaneBufferGeometry(3, 2 ...

experiencing a never-ending loop while attempting to load images through ajax requests

I am attempting to ensure that user uploaded files remain private in node.js. I am utilizing angular to display the file on the client side. <div ng-repeat="message in messages"> <div class="details" ng-if="message.type == 'photo'"& ...

Creating a dynamic web application using Asp .NET Web Api, MVC, and Angular 2, integrating an action that

Working on an ASP .NET MVC application integrated with Angular 2, I encountered a problem when trying to communicate from the angular service to a WebApi Controller. The issue arises when attempting to access an action within the WebApi Controller that req ...

What is the recommended version of Node to install in order to have Angular CLI support?

As a beginner in development, I recently started experimenting with Angular and after successfully installing everything with "npm install -g @angular/cli", I encountered an error when running "ng version". Can someone provide guidance on this issue? I at ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Developing a Simple Analytics Dashboard

As I plan to develop a fundamental Analytics page to delve deeper into Javascript, AJAX and alternative data storage methods like redis, I find myself pondering the optimal way to deliver user data. Should it be dynamically calculated at real-time for gr ...

Encountering MySQL PUT and DELETE Error 500 when using Express and Axios

An unexpected project has landed in my lap, pieced together using tools that are unfamiliar to me. It utilizes Express, Bookshelf, and Axios to connect with a MySQL database. While the GET and PUT routes in Express seem to be functioning properly, issues a ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

Encountering trouble with displaying data in Express and Mongoose

Struggling to comprehend how to define and utilize an API in Express, while using Mongoose to connect with MongoDB. Successfully saving objects from input on the front end, but getting lost when it comes to retrieving and displaying the saved data. Take a ...

The validation directive is run on each individual item within the ng-repeat loop

As I develop a single page application utilizing Angular and Breeze, the challenge of managing entities with dynamic validation arises. With a set of entities displayed on the page using data-ng-repeat, I implement in place validation through toggling betw ...

Is there an npm package that functions like Google's page translator?

Is there an npm package that serves a similar purpose to Google Page Translator? I've integrated it into my Angular project, but I'm curious if there is a version available as an npm package. Click here for image description ...

Tips for setting focus on an input field within a Clarity modalHere are some steps

Currently, I am working with Clarity 3 and Angular 9. In my project, there is a Modal window that contains only one input field. The requirement is that when the modal pops up, the input field should automatically be in a focused state. Below is the code ...

Preserve the XHR-generated configuration when the browser is refreshed

My PHP page features a navigation menu with options such as Home, About Us, and Profile. When clicking on the "About Us" link from the home page, it loads an Ajax response displaying the information without reloading the page. However, if the user decide ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...