我正在尝试调用 API,但我认为出了问题,
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;
})
);
}
}
没有获得任何登录信息Network tab
铬。
我正在使用 Angular 7.0.1 和 Typescript: 3.1.3
这是我的应用程序组件文件
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() {
}
}
该服务已正确添加到 app.module.ts 文件中
暴露的方法HttpClient
通常返回一个 Cold Observable。这本质上意味着这些方法不会进行任何 API 调用,除非它们返回的 Observables 是subscribe
d to.
要解决您的问题:
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);
}
}
在你的组件中:
...
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));
}
...
}
有用的资源:
-
热观测值与冷观测值 https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339- Ben Lesh(RXJS 负责人)。
-
冷与热的观测结果 https://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html- 思想传输。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)