httpClient Angular to PHP проблема отправки данных

У меня есть небольшой проект, который я пытаюсь сделать, где какой-то пользователь может ввести некоторые данные в текстовое поле, которое затем отправляется на php-сервер. Ранее я не использовал angular, когда раньше он работал, но сейчас пытаюсь использовать угловой и php вместе.

Моя проблема в том, что как только я нажимаю «отправить» данные, которые отправляются на .txt файл либо печатает «массив», используя $_POST или ничего не используя $_HTTP_RAW_POST_DATA,

app.component.ts:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
data: string;
userInput: any;
@ViewChild('toSend') input: ElementRef;

constructor(private http: HttpClient) {
}
toSend = JSON.stringify(this.input);
ngOnInit(): void {

}

postData() {
const newInput = {
text: this.input.nativeElement.value
};
console.log(this.input.nativeElement.value);
this.http.post('http://localhost:81/test.php', this.toSend)
.subscribe(
res => {
console.log(res);
}
);
}

requestData() {
this.http.get('http://localhost:81/test.php').subscribe(
data => {
const myJSON = JSON.stringify(data);
console.log(myJSON);
}
);
}
}

PHP:

<?php

echo $_POST;

$myfile = fopen("TestingOut.txt", "a++") or die("Unable to open file!");
$txt = $HTTP_RAW_POST_DATA."\r\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

app.component.html:

 <div style="text-align: center; padding-top: 10px">
<input    type="text"id="inputText"placeholder="Insert Input"#toSend
>
<p></p>
<button type='submit' (click)='postData()' >Submit Data</button>
<br>
<hr>
<button (click)='requestData()'>Request Data</button>
</div>

2

Решение

Если вы обращаетесь к элементу DOM, используя @viewChild вам нужно подождать AfterViewInit ловушка жизненного цикла для доступа к переменной, так как это когда дочерние компоненты, элементы DOM и директивы становятся доступными.
Но это не требуется в вашем случае, так как вы используете переменную ссылки Template, вы можете передать значение элемента управления вводом в качестве параметра для публикации метода данных, используя toSend.value

   <div style="text-align: center; padding-top: 10px">
<input    type="text"id="inputText"placeholder="Insert Input"#toSend
>
<p></p>
<button type='submit' (click)='postData(toSend.value)' >Submit Data</button>
<br>
<hr>
<button (click)='requestData()'>Request Data</button>
</div>

Составная часть:

import { Component, OnInit, ViewChild, ElementRef,AfterViewInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit,AfterViewInit{
data: string;
userInput: any;
toSend:any
@ViewChild('toSend') input: ElementRef;

constructor(private http: HttpClient) {
}

ngOnInit(): void {

}
ngAfterViewInit() {
this.toSend=this.input
}
postData(value) {

this.http.post('http://localhost:81/test.php', value)
.subscribe(
res => {
console.log(res);
}
);
}

requestData() {
this.http.get('http://localhost:81/test.php').subscribe(
data => {
const myJSON = JSON.stringify(data);
console.log(myJSON);
}
);
}
}

Или если вы хотите пойти с @viewChild вам нужно использовать observable,

  import {Observable,fromEvent} from 'rxjs';
import {pluck} from 'rxjs/operators
export class Appcomponent implements OnInit,AfterViewInit{
@ViewChild('toSend') input: ElementRef;
Input$:Observable<any>;
toSend:any
ngAfterViewInit() {
this.Input$=fromEvent(this.input.nativeElement,'input');
this.Input$.pipe(pluck('target','value')).subscribe(value=>{
this.toSend=value;
console.log(this.data)});
}

postData() {

console.log(this.input.nativeElement.value);
this.http.post('http://localhost:81/test.php', this.toSend)
}

fromEvent: Превращает событие в наблюдаемую последовательность
pluck: Выберите свойства для излучения.

1

Другие решения

Других решений пока нет …