首页 > 解决方案 > Angular http.post 不通过订阅发送数据

问题描述

我正在尝试将数据发布到我的 api。post.subscribe 不发送任何数据,也没有抛出错误。API 100% 正常工作。
这是我的代码:
httpservice.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Product } from './Product';
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root',
})

export class HttpService {

  baseURL = 'https://localhost:2403/testapi/';

  constructor(private http: HttpClient) {
    this.products = new Array();
  }
  products: Product[];
  post(product: Product): boolean {
    if ( !this.checkIfProductExistsAlready(product) ) {
      console.log('posting product');

      this.http.post<any>(baseURL,{"product": product.name, "price": 10, "done": false})
        .subscribe((data) => {
          console.log(data);
          product.id = data.id;
          console.log('hi');
        },
        error => console.log('uojdsigdk' + error)
      );
      console.log('posted ' + product.id);
      this.products.push(product);
      return true;
    } else {
      return false;
    }
  }

form.component.ts

addItem(): void {

    this.isError = false;
    if (!this.httpservice.post(new Product(-1, this.name, this.price, 0))) {
      this.isError = true;
    }
}

这是 app.module.ts 中的提供者声明

[...]
  providers: [HttpService],
[...]

这可能是由配置文件引起的吗?

标签: javascriptangularhttpobservable

解决方案


也许这是因为您尝试通过 http 访问本地网络服务器

baseURL = 'https://localhost:2403/testapi/';

否则使用提琴手,在你的 api 上做一个发布请求,看看服务器返回了什么。:)


推荐阅读