Создание POST-запроса на Angular от Сервиса - PullRequest
0 голосов
/ 09 июля 2019

Я пытаюсь создать POST-запрос в Angular v7 из службы.Мой класс обслуживания уже содержит некоторые запросы get, которые извлекают данные из моего API.Теперь мне нужно опубликовать данные, и я не могу понять формат / синтаксис (все еще плохо знакомый с angular).

В 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.");
  }
}

Ответы [ 2 ]

2 голосов
/ 09 июля 2019

Вы не должны подписываться внутри своего сервиса, вместо этого подписывайтесь в компоненте, также return http.post от вашего сервиса

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

и ваш код компонента должен быть,

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

});
0 голосов
/ 09 июля 2019
/**
 * Construct a POST request which interprets the body as JSON and returns it.
 *
 * @return an `Observable` of the body as an `Object`.
 */
post(url: string, body: any | null, options?: {
    headers?: HttpHeaders;
    observe?: 'body';
    params?: HttpParams;
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<Object>;

Это странно, потому что http.post возвращает наблюдаемое и на него можно подписаться

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...