2017-03-16 80 views
0

我有這樣的服務:如何將響應從服務傳遞到組件?

Login (body): Observable<Login[]> { 

     //let bodyString = JSON.stringify(body); // Stringify payload 
     var bodyString = 'email='+body.email +'&password='+body.password; 

     let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'}); 

     let options = new RequestOptions({ headers: headers }); // Create a request option 

     return this.http.post('/logiranje', bodyString, options) // ...using post request 
         .map(response => {return response}) // ...and calling .json() on the response to return data 
         .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any 
    } 

我有分量:

submitLogin(values){ 

      var current = this; 
     // Variable to hold a reference of addComment/updateComment 
     let loginOperation:Observable<any>; 
     loginOperation = this.loginService.Login(values); 
     loginOperation.subscribe(
      (response) => { console.log("Success Response" + response)}, 
      function(error) { console.log("Error happened" + error)}, 
      function(){ 

       current.router.navigate(['/home']); 
       console.log("the subscription is completed"); 


      } 
     ); 

     } 

我要的是檢查:

if(response.isLoggedIn){ 
current.router.navigate(['/home']); 
} 

但我不知道如何從服務傳遞價值零件? 任何建議我該怎麼做?

回答

1

看來,你期望你的迴應是一個JSON。然後,您應該如下圖吧:

return this.http.post('/logiranje', bodyString, options) 
    .map(response => { response.json() }) 
    .catch((error:any) => Observable.throw(error.json().error || 'Server error')); 

既然你已經在你的組件注入你服務,你只好分配給一個變量的響應:

data : any; 

constructor(private loginService : LoginService) {} 

myFunction(body){ 
    this.loginService.Login(body).subscribe(
     res => { this.data = res }, 
     err => { console.log(err) } 
    ); 
} 

然後你可以使用你的data可變

if(this.data.isLoggedIn){ 
    current.router.navigate(['/home']); 
} 
+1

即時得到,當你用你的代碼什麼呢'的console.log(響應)'顯示this.data未定義 – uzhas

+0

錯誤? 您是否像我在第一行中那樣定義了一個'data'變量? – YounesM

+0

「成功ResponseResponse與狀態:200確定爲URL:http:// localhost:3000/logiranje」login.component.js:38:68 訂閱完成 – uzhas

相關問題