首页 > 解决方案 > 从服务在 Angular 中发出 POST 请求

问题描述

我正在努力从服务中创建 Angular v7 中的 POST 请求。我的服务类中已经有一些从我的 api 中提取数据的获取请求。现在我需要发布数据,但我无法弄清楚格式/语法(对于角度来说还是新手)。

在VSCode中我可以看到它说Property 'subscribe' does not exist on type 'void'.

这里是服务

Shipment.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, tap, map } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import { Ziptastic } from '../interfaces/ziptastic';
import { ReturnShipment } from '../interfaces/return-shipment';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};

@Injectable({
  providedIn: 'root'
})
export class ShipmentService {
  private shipmentCreation = 'api/ReturnShipmentQueues';

  constructor(private http: HttpClient) { }
  }

  submitShipment(rShip: ReturnShipment) {
    this.http.post(this.shipmentCreation, rShip, httpOptions)
    .subscribe(
      data => {console.log('AllthePost' + JSON.stringify(data));},
      err => {console.log("error occurred");}
    );

  }
  private handleError(handleError: any): import("rxjs").OperatorFunction<any[], any> {
    throw new Error("Method not implemented.");
  }
}

标签: angularpost

解决方案


您不应该在您的服务中订阅,而是在组件中订阅,以及return您服务中的 http.post

 return this.http.post(this.shipmentCreation, rShip, httpOptions)

你的组件代码应该是,

this.shipmentServic.submitShipment(shipObj).subscribe(response => {

});

推荐阅读