我在点击按钮时调用了以下功能。
login.ts
public login() { this.showLoading() this.http.get('http://laravel.dev/test').map(res => res).subscribe(data => { console.log(data) }, error => { this.showError(error); }); }我希望这个API调用应该来自服务文件。 因为我是Ionic 2的新手,这就是为什么我无法获得如何通过服务调用API以及在login.ts接收它。
auth.service.ts
public login(credentials) { // Here I want to call Above API and return it to the `login.ts` }请帮帮我。
I am calling following function on click of button.
login.ts
public login() { this.showLoading() this.http.get('http://laravel.dev/test').map(res => res).subscribe(data => { console.log(data) }, error => { this.showError(error); }); }What I want that this API call should be come from service file. As I am new to Ionic 2 That's Why I am unable to get how can I call above API through service and receive it in login.ts.
auth.service.ts
public login(credentials) { // Here I want to call Above API and return it to the `login.ts` }Please help me.
最满意答案
http.get请求是一个Observable。 您可以从服务返回observable并在组件/页面中订阅。
auth.service.ts
public login(credentials) { return this.http.get('http://laravel.dev/test').map(res => res.json()) }假设你的http返回json, map函数在解码json响应后返回数据。
login.ts
public login() { this.showLoading() this.authService.login(credentials).subscribe(data => { console.log(data) }, error => { this.showError(error); }, ()=>this.dismissLoading()); }通过组件中的构造函数注入服务并订阅登录功能。
The http.get request is an Observable. You can return the observable from the service and subscribe in the component/page.
auth.service.ts
public login(credentials) { return this.http.get('http://laravel.dev/test').map(res => res.json()) }map function returns the data after decoding the json response assuming your http returns json.
login.ts
public login() { this.showLoading() this.authService.login(credentials).subscribe(data => { console.log(data) }, error => { this.showError(error); }, ()=>this.dismissLoading()); }Inject the service through the constructor in your component and subscribe to the login function.
更多推荐
发布评论