Post 数据从 angular 到 php api 侧

Post data from angular to php api side

这是我的 (login.service.ts) 代码:

private pageURL = 'http://localhost/social/src/app/api/ws/react_signup_login/login.php';
    user = new UserLogin();

    login(value: Object): Observable<any> {
        const body = new URLSearchParams();
        Object.keys(value).forEach(key => {
            body.set(key, value[key]);
        });

        let headers = new Headers();
        headers.append('Content-Type',
            'application/x-www-form-urlencoded');
        return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());
    }

这是我的 login.ts class

export class UserLogin {
    username: string;
    password: string;
    constructor() {
    }
}

在 (login.component.ts)

user = new UserLogin();
login(value) {
        this._loginService.login({value})
            .subscribe(
                response => this.user = response,
                error => console.log(error)
            );
    }

最后我的 (login.php) 我认为错误在这里

header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

$params['username'] = $_POST['username'];
$params['password'] = $_POST['password'];

当我尝试 (var_dump) $params 我得到了这个:

array(2) {
  ["username"]=>
  NULL
  ["password"]=>
  NULL
}

尝试使用:

return this._http.post(this.pageURL, value, {
        headers: headers
    }).map(res => res.json());

其中 value 是您的用户对象

在您的 POST Http 调用中,您应该使用定义的 URLSearchParams 作为正文而不是用户,因为您的用户对象是空的。

login.service.ts 中的 http 调用代码块更改为:

return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());

对此:

return this._http.post(this.pageURL, body.toString(), {
            headers: headers
        }).map(res => res.json());