我正在构建一个应用程序来从Facebook获取一些活动,看看:
EventComponent:
events: Object[] = [];
constructor(private eventService: EventService) {
this.eventService.getAll()
.subscribe(events => this.events = events)
}
EventService:
getAll() {
const accessToken = 'xxxxxxxxxxx';
const batch = [{...},{...},{...},...];
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
}
的AuthenticationService:
getAccessToken() {
return new Promise((resolve: (response: any) => void, reject: (error: any) => void) => {
facebookConnectPlugin.getAccessToken(
token => resolve(token),
error => reject(error)
);
});
}
我有几个问题:
1)如何设置每隔60秒更新一次事件的间隔?
2)accessToken
的价值实际上来自一个承诺,我应该这样做吗?
getAll() {
const batch = [{...},{...},{...},...];
this.authenticationService.getAccessToken().then(
accessToken => {
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
},
error => {}
);
}
3)如果是,我怎么能处理来自getAccessToken()
承诺的错误,因为我只返回观察者?
4)来自post请求的响应默认情况下不会返回一个对象数组,我将不得不进行一些操作。我应该这样做吗?
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
.map(response => {
const events: Object[] = [];
// Manipulate response and push to events...
return events;
})
答案 0 :(得分:0)
5f=0.00000
。setTimeout(() => {},60000)
或error => error
。error => { return error; }
。由于Respons现在是JSON格式,你必须从中获取数组并返回它。在返回之前,您可以进行所需的修改。 随意编辑答案......
答案 1 :(得分:0)
以下是您的问题的答案:
1)您可以利用observables的interval
函数:
getAll() {
const accessToken = 'xxxxxxxxxxx';
const batch = [{...},{...},{...},...];
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return Observable.interval(60000).flatMap(() => {
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json());
});
}
2)您可以在此级别利用可观察量的fromPromise
函数:
getAll() {
const batch = [{...},{...},{...},...];
return Observable.fromPromise(this.authenticationService.getAccessToken())
.flatMap(accessToken => {
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
});
}
3)您可以利用catch
运算符来处理错误:
getAll() {
const batch = [{...},{...},{...},...];
return Observable.fromPromise(this.authenticationService.getAccessToken())
.catch(() => Observable.of({})) // <-----
.flatMap(accessToken => {
const body = `access_token=${accessToken}&batch=${JSON.stringify(batch)}`;
return this.http.post('https://graph.facebook.com', body)
.retry(3)
.map(response => response.json())
});
}
在这种情况下,当获取访问令牌发生错误时,会提供一个空对象来构建POST请求。
4)是的,确定! map
运算符允许您返回所需内容...