2016-03-02 59 views
-1

我有一個頁面,並在角2角2 HTTP許多用戶

服務當我打電話的服務功能this.Auth.login(),它使一個HTTP POST請求。我的問題是,只要請求返回數據,我想在服務和頁面中使用該數據。

我試過各種東西,但無法弄清楚如何去做。

我知道我的代碼不能這樣工作,因爲現在this.Auth.login()返回一個訂戶對象。如果我刪除服務中的'.subscribe()',它將在頁面中工作。但那不是我需要的。

我也嘗試回覆一個承諾,但無法使其工作。

有沒有人知道我可以如何在兩個控制器中獲得來自http.post的數據,並在請求完成後立即使用它?


這裏是我的代碼

頁:

import {AuthService} from '../auth/auth.service'; 

@Page({ 
    templateUrl: 'build/pages/signin/signin.html' 
}) 
export class Signin { 

    constructor(app: IonicApp, auth: AuthService){ 
     this.Auth = auth; 
    } 

    signIn = function() { 
     this.Auth.login(this.user.email, this.user.password) 
      .subscribe(data => {do some stuff here}); 
     // maybe a promise with .then can solve this 
    }; 
} 

服務:

import {Http, Headers} from 'angular2/http'; 
import {Injectable} from 'angular2/core'; 

@Injectable() 
export class AuthService { 
    private http; 

    constructor(http:Http) { 
     this.http = http; 
    } 

    login(email, password) { 
     let headers = new Headers(); 
     headers.append('Content-Type', 'application/json'); 

     // maybe i need to return this as a promise 
     return this.http.post('http://localhost:9000/auth/local', JSON.stringify({ 
        email: email, 
        password: password 
       }), { 
        headers: headers 
       }) 
       .subscribe(data => { 
        do some stuff here too with the data 
       )); 
       // i tried to add .toPromise() but that didn't work 
    } 
} 

我離開了代碼的其他行所以可能會有一些依賴失蹤。雖然這很好。

回答

2

您可以在Servicelogin的正文中使用map。即

.map(data => { 
       do some stuff here too with the data 
       // still bubble up 
       return data; 
      )); 
+0

我想,和我得到的錯誤'this.http.post(.. 。)。地圖不是一個函數。 –

+0

添加導入'rxjs/add/operator/map';在AuthService – Abdulrahman

+0

是否正確地說,除非另外調用'subscribe()'(本例中顯示的服務),否則'map'回調將不會被執行?如果是這樣,那麼需要注意的是,如果您依賴於數據執行操作,無論調用代碼是否在observable上調用「subscribe()」。 – GregL

-1

好吧,我不知道這是否是合法的,但它似乎爲我工作:

var res = this.http.post('http://localhost:9000/auth/local', JSON.stringify({ 
     email: email, 
     password: password 
    }), { 
     headers: headers 
    }); 

res.subscribe(
    data => { 
     console.log('data'); 
    }, 
    err => { 
     console.log('err'); 
    }, 
    () => { 
     console.log('next'); 
    } 
); 

return res; 
+0

'.map()'應該可以工作(即@basarat的答案)。這裏有一個工作plunker:http://plnkr.co/edit/vVL2oskhgH781PUz4yd6?p=preview –