angular - 从服务在 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.");
}
}
解决方案
您不应该在您的服务中订阅,而是在组件中订阅,以及return
您服务中的 http.post
return this.http.post(this.shipmentCreation, rShip, httpOptions)
你的组件代码应该是,
this.shipmentServic.submitShipment(shipObj).subscribe(response => {
});
推荐阅读
- sql-server - MSSQL 邮件权限被拒绝 xp_sysmail_activate
- javascript - 当属性在 REST api 中没有值时应该返回什么?
- python-3.x - acquire_token_by_device_flow 方法未执行
- flutter - 如何将模型列表映射到 Firebase Firestore 中的另一个模型?
- google-maps - 如何使用折线数据创建 Google 静态地图
- postgresql - 运行 docker postrgessql image 两次先退出
- javascript - 页面上的多个倒数计时器
- api - 如何在 Jmeter 请求中处理方括号 []
- java - 如何在 java 中将 POI 工作簿添加为 json 元素
- javascript - 在找到的示例代码中,Array.prototype.find 的箭头函数回调中令人惊讶的语法是什么?