我试着给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中获得任何日志。我使用的是角7.0.1和类型记录: 3.1.3这是我的app组件文件
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文件中。
发布于 2018-12-17 17:40:01
确保将此服务ChatService注入到组件中。
应该将ChatService注册为应用程序模块的提供者或其使用的地方,然后您必须在注入服务的组件中订阅sendMessage。
确保您的服务已在app.module的提供程序列表中注册,或将Injectable声明放在顶部:
@Injectable({
providedIn: 'root',
})以下是Range7中常见的服务示例:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ChatService{
constructor() { }
}发布于 2018-12-17 17:46:56
HttpClient公开的方法通常返回一个可观察到的冷值。这在本质上意味着这些方法不会进行任何API调用,除非它们返回的可观测值是subscribed。
要解决您的问题:
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));
}
...
}有用的资源:
发布于 2018-12-17 17:39:00
您必须订阅.subscribe()可以观察到的内容
顺便问一句:你为什么要映射到相同的值?
map(response => {
return response;
})https://stackoverflow.com/questions/53820361
复制相似问题