Ad

Angular 8 - Cannot Get HttpClient POST To Do Its Work Maybe In Conjunction With Socket.io?

- 1 answer

I had a working AngularJS Frontend and a backend written in node.js' express, http and socket.io. Now I want to translate the frontend to Angular 8 and further use the old backend (because it worked well and was a ton of work).

Now I use ngx-socket-io for the chat communication and want to use the HttpClientModule of Angular for the API-requests.

app.module.ts

...
import { HttpClientModule } from '@angular/common/http';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
...
const apiConfig: SocketIoConfig = { url: 'http://localhost:8000', options: {} };

@NgModule({declarations: [...], imports: [
  ...
  HttpClientModule,
  SocketIoModule.forRoot(apiConfig)
]
...

login.component.ts

import { CommunicationService } from '../services/communication.service';
...
constructor(
  ...
  private comm: CommunicationService
) { }

submitForm() {
  const formValue = this.loginGroup.value;
  this.comm.checkAuthentication(formValue.userName, formValue.password);
}

communication.service.ts

import { Socket } from 'ngx-socket-io';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
...
@Injectable({
  providedIn: 'root'
})
export class CommunicationService {
  private api = 'http://localhost:8001/api';
  constructor(private socket: Socket, private http: HttpClient) { }

  checkAuthentication(username: string, password: string) {
    console.log(`send: ${username}, ${password}`);
    const test = this.http.post<any>(
      `${this.api}/authenticate`,
      { username, password }
    ).pipe(
      catchError(this.errorHandler)
    );
    console.log(test);
    const test2 = this.http.get(
      `${this.api}/users`
    );
    console.log(test2);
  }
  ...
}

I can see the request going out, but on the server side it doesn't arrive. I would see a log entry there. If I use postman I see the request arriving, so the server still works.

I could imagine that angular has a problem with the constantly open connection on port 8000 to the socket.io and then use the same socket to throw a request on. Could that be? And yes, the site uses a chat (works on sockets) and some other features that work by api requests. So I need both options working together.

edit: I changed the port of the api to 8001 and it still gets no response. The console.log shows a nearly complete empty object:

{…} ​_isScalar: false ​operator: Object { selector: errorHandler() , caught: {…} } ​source: Object { _isScalar: false, source: {…}, operator: {…} }

Ad

Answer

Http client returns an observable so You have to subscribe on it to catch the data , please check this ref

this.http.post<any>(
      `${this.api}/authenticate`,
      { username, password }
    ).pipe(
      catchError(this.errorHandler)
    ).subscribe((data) => {
         console.log(data) 
    });
Ad
source: stackoverflow.com
Ad