I'm probably missing something very obvious, but what I am trying to do is share data that I get from a server asynchronously, between components.
This is what my service looks like:
import {Injectable} from 'angular2/core';
import {ApiService} from './api.service';
@Injectable()
export class UserService {
private user: Object
constructor(private _api: ApiService) {}
getUser(user) {
return this.user
}
setUser(slug) {
return Promise.resolve(this._api.GET('users/' + slug + '/?slug=true').subscribe(
data => { this.user = data.json; return data.json; },
(err)=>console.log(err)
))
}
}
Since the process is asynchronous I need to Promise the response, however the promised response returns the actual subscribe object, not the returned data.json
.
This is for a profile page, it consists of nested routes, so I can't pass data to the routed components. One of the routed components is Posts, and after loading the profile, this should start fetching posts OF THE CURRENT USER IN THE SERVICE.
So this is what I need to happen:
- User goes to his/her profile.
- Service calls setUser('foo'), once response, show profile page.
- Fetch the user's post into the Posts component using the service's getUser()
The api service looks like this:
import {Injectable} from 'angular2/core';
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';
import {GlobalService} from '../app.service';
import 'rxjs/Rx';
@Injectable()
export class ApiService {
constructor(private http: Http) {}
apiURL = 'http://localhost:8000/api/';
assetURL = 'http://localhost:8000/media/';
GET(url) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
headers.append("Content-Type", 'application/json');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
var requestoptions = new RequestOptions({
method: RequestMethod.Get,
url: this.apiURL + url,
headers: headers
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
if (res) {
return { status: res.status, json: res.json() }
}
});
}
}
Excuse the poor question if it was, I am still learning angular2 and couldn't find a concrete solution to this online.