У меня есть небольшой проект, который я пытаюсь выполнить, где какой-то пользователь может ввести некоторые данные в текстовое поле, которое затем отправляется на сервер php, я раньше не использовал angular, когда он работал раньше, но теперь я пытаюсь использовать 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.info(this.input.nativeElement.value);
this.http.post('http://localhost:81/test.php', this.toSend)
.subscribe(
res => {
console.info(res);
}
);
}
requestData() {
this.http.get('http://localhost:81/test.php').subscribe(
data => {
const myJSON = JSON.stringify(data);
console.info(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>






Если вы обращаетесь к элементу DOM с помощью @viewChild, вам нужно подождать, пока ловушка жизненного цикла AfterViewInit получит доступ к переменной, поскольку именно тогда станут доступны дочерние компоненты, элементы DOM и директивы.
Но в вашем случае это не требуется, поскольку вы используете ссылочную переменную шаблона, вы можете передать значение элемента управления вводом в качестве параметра для метода публикации данных с помощью 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.info(res);
}
);
}
requestData() {
this.http.get('http://localhost:81/test.php').subscribe(
data => {
const myJSON = JSON.stringify(data);
console.info(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.info(this.data)});
}
postData() {
console.info(this.input.nativeElement.value);
this.http.post('http://localhost:81/test.php', this.toSend)
}
fromEvent: превращает событие в наблюдаемую последовательность
pluck: выберите свойства для испускания.
Рад, что смог помочь товарищу :)
Попробуйте написать dd ($ _ POST); на стороне php вместо echo $ _POST; чтобы вы могли понять структуру того, что вы получаете