这个问题在这里已有答案:
我可能错过了一些非常明显的东西,但我想要做的是分享我从服务器异步获取的数据,在组件之间 .
这就是我的服务:
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)
))
}
}
由于进程是异步的,我需要Promise响应,但是承诺的响应返回实际的subscribe对象,而不是返回的 data.json
.
这是一个配置文件页面,它由嵌套路由组成,因此我无法将数据传递给路由组件 . 其中一个路由组件是Posts,加载配置文件后,应该开始提取帖子 OF THE CURRENT USER IN THE SERVICE .
所以这就是我需要发生的事情:
-
用户转到他/她的 Profiles .
-
服务调用setUser('foo'),一旦响应,显示 Profiles 页面 .
-
获取用户's post into the Posts component using the service' s getUser()
api服务看起来像这样:
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() }
}
});
}
}
请原谅这个可怜的问题,如果是的话,我还在学习angular2,并且无法在网上找到具体的解决方案 .
2 回答
如果你需要一个承诺,你可以使用这样的东西:
否则您解决订阅而不是收到的数据......
如果你需要
Promise
,你可以使用toPromise