Working with data returned from an http post request in both a service and a page in Angular 2 can be tricky.
The challenge arises when calling the service function this.Auth.login()
, which initiates the http post request. Upon receiving the data from the request, the goal is to manipulate it in both the service and the page simultaneously.
Despite trying various approaches, finding a solution has proven elusive so far.
The issue lies in the fact that this.Auth.login()
currently returns a subscriber object. Removing the '.subscribe()' allows it to work in the Page but fails to meet the requirement of processing the data in both contexts.
Attempts to utilize promises have also been unsuccessful.
Is there a method or technique to access the data from the http.post
in both controllers and begin working with it upon completion of the request?
Here's my code
Page:
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
};
}
Service:
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
}
}
I left out the other lines of code so there might be some dependencies missing. It's all good though.