Angular 7 API没有被调用

时间:2018-12-17 17:35:25

标签: angular typescript

我正在尝试调用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的chrome日志。 我正在使用angular 7.0.1和打字稿: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文件中

3 个答案:

答案 0 :(得分:2)

确保将此服务ChatService注入组件中。

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

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

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

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

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

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

export class ChatService{

  constructor() { }

}

答案 1 :(得分:0)

您必须使用.subscribe()订阅您的可观察对象

顺便说一句:为什么要映射到相同的值?

Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.setData(Uri.parse("smsto:" + Uri.encode(MobileNumber)));
smsIntent.putExtra("exit_on_sent", true); //this line doesn't work
startActivity(smsIntent);

答案 2 :(得分:0)

HttpClient公开的方法通常返回Cold Observable。从本质上讲,这意味着这些方法将不会进行任何API调用,除非它们返回的Observables被subscribe定向到。

要解决您的问题,

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

  ...

}

有用的资源:

  1. Hot vs Cold Observables-作者:Ben Lesh(RXJS负责人)。
  2. COLD VS HOT OBSERVABLES-Thoughtram。