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