Невозможно отправить запрос POST. Не удается прочитать свойство 'post' из неопределенного - PullRequest
0 голосов
/ 01 июня 2019

Итак, я прошел через большинство подобных вопросов на GitHub и StackOverflow.

В файле my issue.component.ts я привязал значение раскрывающегося меню к переменной issueInformation.Теперь мне нужно отправить эти данные на сервер, и я использую запрос для этого.

Это мой issue.component.ts файл:

import { Component, OnInit, DoCheck } from '@angular/core';
import { IssuesService } from '../issues.service';
import { HttpClientModule } from '@angular/common/http';
import { Http } from '@angular/http';



@Component({
  selector: 'app-issue',
  templateUrl: './issue.component.html',
  styleUrls: ['./issue.component.css']
})
export class IssueComponent implements OnInit,  DoCheck {

issueInfo: any[] = [];
issueInformation: any;
    httpClient: any;
    http: any;
  constructor(private issue: IssuesService) { }
ngDoCheck(): void {
        console.log('issue:', this.issueInformation);
    }

  ngOnInit() {
    this.getIssues();
  }
    getIssues() {

        console.log('issue::', this.issueInformation);

        this.issue.allIssues().
    subscribe(
      data2 => {
          this.issueInfo = data2.Issues;

      },
      err => console.log(err),
      () => console.log('complete')
    );

  }


}

Поскольку я новичок в Angular, я попробовал один из примеров с запросом POST и добавил его в этот файл после getIssues() function:

doPOST() {
  console.log("POST");
  let url = `${this.apiRoot}/post`;
  this.http.post(url, {moo:"foo",goo:"loo"}).subscribe(res => console.log(res.json()));
}

Я также попытался добавить (change)="doPOST($event.target.value)" в мою строку выбора в HTML.

Ошибка, которую я получаю:

AppComponent.html:1 ERROR TypeError: Cannot read property 'post' of undefined
    at IssueComponent.getIssues (issue.component.ts:30)
    at IssueComponent.ngOnInit (issue.component.ts:24)
    at checkAndUpdateDirectiveInline (core.js:24489)
    at checkAndUpdateNodeInline (core.js:35151)
    at checkAndUpdateNode (core.js:35090)
    at debugCheckAndUpdateNode (core.js:36112)
    at debugCheckDirectivesFn (core.js:36055)
    at Object.eval [as updateDirectives] (AppComponent.html:7)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:36043)
    at checkAndUpdateView (core.js:35055)

Я попробовал следующее: constructor{private issue: IssuesService,private http: Http} Но это не работает для меня.

Я также пытался сместить функцию doPOST () в файле issues.service.ts, но я не могу вызвать ее в файле issue.component.ts.

Вот файл issues.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Response, Headers, RequestOptions} from '@angular/http';
import { Observable} from 'rxjs';
import { IssueComponent } from './issue/issue.component';


@Injectable({
  providedIn: 'root'
})


export class IssuesService {

  url = 'http://localhost:8080/issueTypes';
_baseUrl = 'http://localhost:8080';
  constructor(private http: HttpClient) { }

  allIssues(): Observable<any> {
    return this.http.get(this.url);
  }
 doPost() {
      console.log('POST');
      const url = '/api/issue';
      this.http.post(url, {moo: 'foo', goo: 'loo'}).subscribe(res => console.log(res.json()));
                                          }
}

Может кто-нибудь сказать, пожалуйста, что идет не так?Если то, что я делаю, не правильно с самого начала, то, пожалуйста, скажите мне, как я могу отправить обратно значение issueInformation на сервер?

1 Ответ

1 голос
/ 02 июня 2019

Потратив целый день, пытаясь выяснить это, я нашел решение:

constructor(private issue: IssuesService, private httpClient: HttpClient) { }

И после добавления этого запрос POST можно поместить в тот же файл, что иissue.component.ts следующим образом:

postIssue() {
      this.httpClient.post('http://localhost:8080/uploadFile', 
      {issueInformation: this.issueInformation}).subscribe((data: any) => 
      console.log(data));
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...