1
我目前正在使用Ruby on Rails作为后端的Ionic 2。我面临的问题是我无法理解Observable和Promises。它们是相互关联的吗?现在我试图在POST请求使用头进行身份验证后检索数据。获取数据头标授权离子2
//clocks.ts (Provider)
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';
@Injectable()
export class Clocks {
baseUrl: string = "http://localhost:3000/api/v1"
token: any;
constructor(public http: Http, public storage: Storage) {}
getAttendanceInfo() {
return new Promise((resolve,reject) => {
// Load token
this.storage.get('token').then((value) => {
this.token = value;
let headers = new Headers();
headers.append('Authorization', 'Token ' + this.token);
this.http.get(this.baseUrl + '/attendances.json', {headers: headers})
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
})
});
});
}
在出席第
//attendance.ts (Page)
loadAttendance() {
this.clocks.getAttendanceInfo().then(res => {
let response = (<Response>res).json();
this.attendance = response.data;
console.log(this.attendance)
})
}
这里是我的问题。
在这种情况下,我可以使用Observable来获得与getAttendanceInfo()方法相同的结果吗?他们如何工作?
此外,有没有什么办法可以从存储器中为每个页面请求检索令牌,而不用重写相同的头文件代码?例如。一种方法可以始终用于从存储中检索令牌并追加到头部。
非常感谢,如果你们能清除我的困惑。