我有这项服务:
Login (body): Observable<Login[]> {
//let bodyString = JSON.stringify(body); // Stringify payload
var bodyString = 'email='+body.email +'&password='+body.password;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post('/logiranje', bodyString, options) // ...using post request
.map(response => {return response}) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Server error' )); //...errors if any
}
我有组件:
submitLogin(values){
var current = this;
// Variable to hold a reference of addComment/updateComment
let loginOperation:Observable<any>;
loginOperation = this.loginService.Login(values);
loginOperation.subscribe(
(response) => { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function(){
current.router.navigate(['/home']);
console.log("the subscription is completed");
}
);
}
我想要的是检查:
if(response.isLoggedIn){
current.router.navigate(['/home']);
}
但我不知道如何将价值从服务转移到组件? 任何建议我怎么能这样做?
答案 0 :(得分:1)
您似乎希望自己的回复是JSON。然后,您应该将其映射如下:
return this.http.post('/logiranje', bodyString, options)
.map(response => { response.json() })
.catch((error:any) => Observable.throw(error.json().error || 'Server error' ));
由于您已经在组件中注入了服务,因此您只需将响应分配给变量:
data : any;
constructor(private loginService : LoginService) {}
myFunction(body){
this.loginService.Login(body).subscribe(
res => { this.data = res },
err => { console.log(err) }
);
}
然后您可以使用data
变量
if(this.data.isLoggedIn){
current.router.navigate(['/home']);
}