Angular 7 API没有被调用 [英] angular 7 api not getting called

查看:81
本文介绍了Angular 7 API没有被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用API,但我认为出了点问题,

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;
                })
            );
    }

}

没有在chrome的Network tab中获取任何日志. 我正在使用angular 7.0.1和打字稿:3.1.3 这是我的应用程序组件文件

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() {
  }
}

该服务已正确添加到app.module.ts文件中

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

推荐答案

请确保已在组件中注入此服务ChatService.

Make sure that you inject this service ChatService in your component.

ChatService应该注册为应用模块或其使用位置的提供者,然后您必须在注入服务的组件中订阅sendMessage.

ChatService should be registered as providers to the app module or where it's used and then you have to subscribing to sendMessage at in the component where service is injected.

确保您的服务已在app.module的提供程序列表中注册,或顶部具有Injectable声明:

Make sure your service is registered in list of providers at app.module or has the Injectable declaration at top:

@Injectable({
  providedIn: 'root',
})

角度7中一个常见的服务示例如下:

a common example of service in angular 7 is below:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})

export class ChatService{

  constructor() { }

}

这篇关于Angular 7 API没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆