我正在尝试将我的表单从angular 5发送到我的php文件,并重新注入 结果回到角度
/* My typescrit file */
import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
import { trigger , state, style, transition, animate, keyframes } from
'@angular/animations';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { MatButtonModule, MatCardModule, MatMenuModule, MatToolbarModule,
MatIconModule, MatCheckboxModule, MatRadioModule, MatSelectModule,
MatInputModule, MatDialogModule, MatTooltipModule, MatSnackBarModule,
MatSidenavModule } from '@angular/material';
import { ReactiveFormsModule, FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
constructor(public http: HttpClient) {}
let formdata = document.querySelector('form');
let datajson= {
action: 'login',
username: formdata.username.value,
useremail: formdata.useremail.value,
usersubject: formdata.usersubject.value,
usermessage: formdata.usermessage.value
};
let apiurl = '../../assets/php/message.php';
this.http.post(apiurl,datajson)
.subscribe(data => {alert(data.data)})
.catch(error=>{ alert (error.status)});
</pre>
但我得到了“Http undefined error”。
答案 0 :(得分:-1)
您可以通过从角度控制器向php页面发送get或post请求来实现此目的。示例代码应该是这样的(它来自我的网站):
app.controller('sign_up', function ($scope, $http) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/
$scope.check_credentials = function () {
document.getElementById("message").textContent = "";
var request = $http({
method: "post",
url: window.location.href + "login.php",
data: {
email: $scope.email,
pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
document.getElementById("message").textContent = "You have login successfully with email "+data;
});
}
答案 1 :(得分:-1)
http未定义,因为您尝试使用它而不在类中定义它。
我猜这个文件显示的是你的 app.module.ts ? 如果是这样,请在那里导入 HttpClientModule 。
import { HttpClientModule } from '@angular/common/http';
...
imports: [
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
转到 app.component.ts 并在那里提出您的请求。或者在任何你希望它完成的组件中。
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
datajson= {
action: 'login',
username: formdata.username.value,
useremail: formdata.useremail.value,
usersubject: formdata.usersubject.value,
usermessage: formdata.usermessage.value
};
apiurl = '../../assets/php/message.php';
constructor(private http: HttpClient) {
this.http.post(apiurl, datajson).subscribe(data => {alert(data.data)}
.catch(error=> {alert(error)}
}
}