我有一个页面,并在角2角2 HTTP许多用户
服务当我打电话的服务功能this.Auth.login()
,它使一个HTTP POST请求。我的问题是,只要请求返回数据,我想在服务和页面中使用该数据。
我试过各种东西,但无法弄清楚如何去做。
我知道我的代码不能这样工作,因为现在this.Auth.login()
返回一个订户对象。如果我删除服务中的'.subscribe()',它将在页面中工作。但那不是我需要的。
我也尝试回复一个承诺,但无法使其工作。
有没有人知道我可以如何在两个控制器中获得来自http.post
的数据,并在请求完成后立即使用它?
这里是我的代码
页:
import {AuthService} from '../auth/auth.service';
@Page({
templateUrl: 'build/pages/signin/signin.html'
})
export class Signin {
constructor(app: IonicApp, auth: AuthService){
this.Auth = auth;
}
signIn = function() {
this.Auth.login(this.user.email, this.user.password)
.subscribe(data => {do some stuff here});
// maybe a promise with .then can solve this
};
}
服务:
import {Http, Headers} from 'angular2/http';
import {Injectable} from 'angular2/core';
@Injectable()
export class AuthService {
private http;
constructor(http:Http) {
this.http = http;
}
login(email, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
// maybe i need to return this as a promise
return this.http.post('http://localhost:9000/auth/local', JSON.stringify({
email: email,
password: password
}), {
headers: headers
})
.subscribe(data => {
do some stuff here too with the data
));
// i tried to add .toPromise() but that didn't work
}
}
我离开了代码的其他行所以可能会有一些依赖失踪。虽然这很好。
我想,和我得到的错误'this.http.post(.. 。)。地图不是一个函数。 –
添加导入'rxjs/add/operator/map';在AuthService – Abdulrahman
是否正确地说,除非另外调用'subscribe()'(本例中显示的服务),否则'map'回调将不会被执行?如果是这样,那么需要注意的是,如果您依赖于数据执行操作,无论调用代码是否在observable上调用“subscribe()”。 – GregL