我现在正面临Angular应用程序的问题。我想使用http.post动作将formdata发送到我的php api端点。这是有效的,因为它确实将数据发布到我的php api端点。
但不知何故,它不会返回正确的数据,这是另一个组件所需要的。
执行http.post函数的组件:
import { Component, OnInit, Input } from '@angular/core';
import { DataDevicesService } from '../data-devices.service';
import { NgForm } from '@angular/forms';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { AuthenticationService } from '../authentication.service';
declare var jquery:any;
declare var $ :any;
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
//authenticationKey: any = [];
authenticationKey: string;
authenticationToken: any = [];
authenticationUrl = 'http://192.168.33.10/fortimanager/v1/api.php?login=authenticate';
headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
constructor(private http: HttpClient, private authentication: AuthenticationService) { }
@Input() title: string;
ngOnInit() {
// this.authenticationKey = null;
this.executeAuthentication();
}
executeAuthentication() {
this.http.post(this.authenticationUrl, this.authenticationKey, {headers: this.headers}).subscribe(
res => this.authenticationToken = res);
}
executeTest() {
return this.executeAuthentication();
}
onSubmit(f: NgForm) {
this.authenticationKey = "key=" + f.value["key"];
// DO SOMETHING WITH THE AUTHENTICATION TOKEN, LOGIC COMES HERE
this.executeAuthentication();
this.authentication.setToken(this.authenticationToken);
console.log(this.authentication.getToken());
$('#authenticateModal').modal('hide');
//location.reload();
}
}
PHP api端点(非常简单,仅用于测试目的):
if ($_GET['login'] == 'authenticate'){
if ($_POST['key'] == 'abcd') {
echo '{ "token": "123456" }';
} else {
echo '{ "token": "failure" }';
}
将处理api端点返回到其他组件的服务:
import { Injectable } from '@angular/core';
@Injectable()
export class AuthenticationService {
verifiedToken: string;
constructor() { }
getToken() {
return this.verifiedToken;
}
setToken(receivedToken) {
this.verifiedToken = receivedToken;
}
}
api端点传回的输出是{token:“failure”},这是不行的。
有人可以帮帮我吗?谢谢!
答案 0 :(得分:0)
更改为
async onSubmit(f: NgForm) {
this.authenticationKey = "key=" + f.value["key"];
// DO SOMETHING WITH THE AUTHENTICATION TOKEN, LOGIC COMES HERE
await this.executeAuthentication();
this.authentication.setToken(this.authenticationToken);
console.log(this.authentication.getToken());
$('#authenticateModal').modal('hide');
//location.reload();
}