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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With