【发布时间】:2017-08-09 20:12:02
【问题描述】:
你能告诉我哪里错了吗?当我使用邮递员时,它就可以工作了。但是为什么我不能使用 Angular2 做同样的事情呢?这里的后端 api 来自 PHP。我以前从未使用过 PHP 后端。这与普通的 ASP.net Web Api 有什么不同?我的意思是我们必须发送参数的方式和所有...
Service.ts
import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AuthenticationData {
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login";
constructor(public http: Http) {
}
//to login
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
/*let body = {
username: username,
password: password,
}*/ Not working this too :(
let body='username=myname&password=admin';//I tried hardcode value.But not working
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
login.ts
//to login
loginUser(): void {
if (this.loginForm.valid) {
this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password).subscribe(
data => {
this.response = data;
},
err => {
console.log(err);
},
() => console.log('Complete')
);
}
}
错误:
body: "{"error":"Invalid Request type","status":"201"}", status: 200, ok: true, statusText: "OK",
PHP:
<?php
class ControllerApiLogin extends Controller {
private $error = array();
public function index() {
$json = array();
if (($this->request->server['REQUEST_METHOD'] == 'POST') && !empty($this->request->get['username']) && !empty($this->request->get['password'])) {
if(!empty($this->request->get['username']) && !empty($this->request->get['password'])){
$this->load->language('common/login');
$this->document->setTitle($this->language->get('heading_title'));
// User
$this->registry->set('user', new Cart\User($this->registry));
if ($this->validate()) {
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
if($token_count==0)
{
$this->session->data['token'] = $token;
}else{
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
$this->session->data['token'] = $token;
}
$this->load->model('user/user');
$user_info = $this->model_user_user->getUserByEmail($this->request->get['username']);
$tokeninfo = array();
if(count($user_info) > 0){
$tokeninfo = array(
'token' => $token,
'user_id' => $user_info['user_id'],
'ip' => $this->request->server['REMOTE_ADDR']
);
$date_expired = $this->model_user_user->addUserapitoken($tokeninfo);
}else{
$date_expired = '';
}
$json['token'] = $token;
$json['date_expired'] = $date_expired;
$json['status'] = '200';
}else{
$json['error'] = "No match for Username and/or Password.";
$json['status'] = '201';
}
}else{
$json['error'] = 'Something Went Wrong!!! <br> PLease Enter Correct Login Credentials!!!';
$json['status'] = '201';
}
//$this->response->addHeader('Content-Type: application/json');
//$this->response->setOutput(json_encode($json));
}
else{
$json['error'] = 'Invalid Request type';
$json['status'] = '201';
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->addHeader('HTTP/1.1'.$json['status']);
$this->response->setOutput(json_encode($json));
}
protected function validate() {
//$this->registry->set('user', new Cart\User($this->registry));
if (!isset($this->request->get['username']) || !isset($this->request->get['password']) || !$this->user->login($this->request->get['username'], html_entity_decode($this->request->get['password'], ENT_QUOTES, 'UTF-8'))) {
$this->error['warning'] = $this->language->get('error_login');
}
return !$this->error;
}
}
【问题讨论】:
-
你接收的是 json 格式的数据吗?
-
是的。 @suraj
-
然后检查我的答案..您正在作为表单字符串发送..
标签: php angular ionic-framework ionic2 observable