简体   繁体   中英

Angular http.post not sending data with subscribe

I am trying to post data to my api. The post.subscribe does not send any data, no error is being thrown. The API is 100% working.
Here is my code:
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;
    }
}

This is the provider declaration in the app.module.ts

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

Is it possible that this is caused by a config file?

Maybe this happens because you try to access the local webserver over http s ?

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

Otherwise use fiddler, do a post request on your api and look what the server is returning. :)

I think baseURL is undefined inside your function scope. Try this.baseURL instead. Also make sure your local webserver is serving HTTPS, as mentioned before

this.http.post<any>(baseURL, product);

becomes

this.http.post<any>(this.baseURL, product);

On a side node, a couple of things are potentially wrong with your Observable code, as well as the way you are injecting your Service in your app, as has been mentioned in comments.

add response type

addItem(): void {    
    this.isError = false;
    if (!this.httpservice.post(new Product(-1, this.name, this.price, 0), { observe: 'response',responseType: 'text' })) {
      this.isError = true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM