I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server.
Here is an example of what my service code 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)
))
}
}
Due to the asynchronous nature of the process, I need to use a Promise for the response. However, the promised response seems to return the subscribe object instead of the expected data.json
.
The scenario involves a profile page with nested routes, where passing data to routed components is not feasible. One of these routed components is "Posts," and after loading the profile, it should begin fetching posts OF THE CURRENT USER IN THE SERVICE.
Here's what needs to happen:
- User navigates to their profile.
- Service calls setUser('foo'), displays profile page upon response.
- Fetches the user's posts into the Posts component using the service's getUser()
This is how the API service is structured:
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() }
}
});
}
}
Please excuse any confusion in my query as I am still learning Angular 2 and haven't found a definitive solution online.