如何在Iconic2中使用API调用(How to use API call in service in Iconic2)

编程入门 行业动态 更新时间:2024-10-09 06:25:14
如何在Iconic2中使用API调用(How to use API call in service in Iconic2)

我在点击按钮时调用了以下功能。

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.

更多推荐

本文发布于:2023-08-06 09:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448347.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   API   call   service

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!