2017-02-28 46 views
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) 
    }) 
} 

这里是我的问题。

  1. 在这种情况下,我可以使用Observable来获得与getAttendanceInfo()方法相同的结果吗?他们如何工作?

  2. 此外,有没有什么办法可以从存储器中为每个页面请求检索令牌,而不用重写相同的头文件代码?例如。一种方法可以始终用于从存储中检索令牌并追加到头部。

非常感谢,如果你们能清除我的困惑。

回答

1

我找到了解决方案。

您可以创建身份验证作为服务提供者的一部分。对于这种情况,我使用localStorage。对于备注,令牌的结构也依赖于您的后端。对于我来说,我使用authentication_with_http_token从Rails的方法,该结构是这样的

GET /attendances HTTP/1.1 
Host: localhost:3000 
Authorization: Token token=123123123 

我们必须匹配。

// ../providers/auth.ts 

import { Injectable } from '@angular/core'; 
import { Http, Headers } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class Auth { 

    constructor(public http: Http) {} 

    createAuthorizationHeader(headers: Headers) { 
    headers.append('Authorization', 'Token ' + window.localStorage.getItem('token')); 
    } 
} 

温你们返回一个http请求,它以Observable格式返回。除非你想转换成承诺,否则你不需要做任何事情。

// ../pages/attendances/attendances.ts 

import { Component } from '@angular/core'; 

import { NavController } from 'ionic-angular'; 
import { Auth } from '../../providers/auth'; 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'home.html' 
}) 

const baseUrl: string = 'http://localhost:3000/api/v1/'; 

export class HomePage { 

    constructor(public navCtrl: NavController, public auth: Auth) {} 

    ionViewDidLoad() { 
    this.getAttendances(); 
    } 

    getAttendances() { 
    return this.http.get(baseUrl + 'bookings.json', { headers: headers }) 
     .map(data => { 
     // convert your data from string to json 
     data = data.json(); 
     }) 
     .subscribe(response => { 
     // to subscribe to the stream for the response 
     console.log(response); 
     // you can save your response in object based on how you want it 
     }) 
    }