Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 7 api not getting called

I am trying to call API but i think something is wrong,

import { map } from "rxjs/operators";
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

export class Message {
    constructor(public text: any, public sentBy: any) { }
}

@Injectable()
export class ChatService {
    constructor(public http: HttpClient) {
    }

    public sendMessage(message) {
        const usertext = new Message(message, 'user');
        console.log("message send",usertext);
       return this.http
            .post<any>(`http://locahost:3000/api/text_query`, usertext)
            .pipe(
                map(response => {
                    return response;
                })
            );
    }

}

Not getting any logs in Network tab of chrome. I am using angular 7.0.1 and typescript: 3.1.3 Here is my app component file

import {Component, OnInit} from '@angular/core';
import {ChatService} fom './chat.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  message: string;
  constructor(private chatService: ChatService) {}

  sendMessage() {
    this.chatService.sendMessage(this.message).subscribe(res=>{
    })
  }
  ngOnInit() {
  }
}

the service is properly added in app.module.ts file

like image 606
Nikhil Savaliya Avatar asked Feb 17 '26 12:02

Nikhil Savaliya


1 Answers

Methods exposed by the HttpClient generally return a Cold Observable. It would essentially mean that these methods won't make any API call unless the Observables that they return are subscribed to.

To fix your issue:

import { map } from "rxjs/operators";
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

export interface Message {
  public text: any;
  public sentBy: any;
}

@Injectable()
export class ChatService {
  constructor(public http: HttpClient) {}

  public sendMessage(message) {
    const usertext: Message = { text: message, sentBy: 'user' };
    return this.http
      .post<any>(`http://locahost:3000/api/text_query`, usertext);
  }

}

And in your Component:

...
import { ChatService } from "path-to-chat-service";

@Component({...})
export class ChatComponent {
  constructor(private chatService: ChatService) {}

  sendMessage(message) {
    this.chatService.sendMessage(message)
      .subscribe(res => console.log(res));
  }

  ...

}

Helpful Resources:

  1. Hot vs Cold Observables - By Ben Lesh(RXJS Lead).
  2. COLD VS HOT OBSERVABLES - Thoughtram.
like image 141
SiddAjmera Avatar answered Feb 20 '26 01:02

SiddAjmera