简体   繁体   English

如何将响应从服务传递到组件?

[英]How to pass response from service to component?

I have this service: 我有这项服务:

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
    }

I have component: 我有组件:

  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");


             }
        );

       }

What i want is to check : 我要检查的是:

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

But i dont know how to pass value from service to component? 但是我不知道如何将价值从服务传递到组件? Any suggestion how can i do that? 任何建议,我该怎么做?

It seems that your you expect your response to be a JSON. 您似乎希望您的响应是JSON。 You should then map it as below : 然后,您应将其映射如下:

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

Since you already injected your service in your component you'll just have to assign the response to a variable : 由于您已经将服务注入组件中,因此只需将响应分配给变量:

data : any;

constructor(private loginService : LoginService) {}

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

Then you can use your data variable 然后您可以使用data变量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM