import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
// import 'rxjs/add/operator/toPromise';
@Injectable()
export class AccessService {
private baseUrl = '';
constructor(private http: Http) {
}
login(email: string, password: string) {
// var loginUrl = 'http://localhost:8000/app.php/api/login_check'; // url to web API
var loginUrl = this.baseUrl + 'api/login_check'; // url to web API
let user = JSON.stringify({ _username: email, _password: password });
console.log(user);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http
.post(loginUrl, user, options)
.map(this.extractData)
.catch(this.handleError);
}
register(email: string, password: string, password2: string) {
var loginUrl = this.baseUrl + 'register/'; // url to web API
var fos_user_registration_form = {
username: email,
email: email,
plainPassword: { first: password, second: password2 },
roles: ['ROLE_CLIENT']
};
let user = JSON.stringify({
fos_user_registration_form
});
console.log(user);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
if (password === password2) {
return this.http
.post(loginUrl, user, options)
.map(this.extractData)
.catch(this.handleError);
} else {
alert('Las Contraseñas No Coinciden');
}
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body.data || {};
}
private handleError(error: Response | any) {
// in a real world app, we might use a remote logging infrastructure
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.toString());
return Observable.throw(errMsg);
}
我试图用角度2做一个简单的帖子但是返回这个异常EXCEPTION:this.http.post不是一个函数,我不确定是错误的,请帮帮我。在它工作之前,我将项目克隆到另一个文件夹中,这对我不起作用。
答案 0 :(得分:2)
您很可能没有在HttpModule
中提供app.module.ts
(或者是其中的任何一个模块)。确保您拥有以下内容:
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
....
],
imports: [
HttpModule,
...
],
...
});