本文主要介绍ionic3+angular4实现接口请求及本地json文件读取示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。
一 准备工作
首先,ionic3+Angular4的开发环境你得有,这里就不赘述。环境准备好,创建一个空白项目,模板自选。
二 实现过程
1 新建json文件和service
service记得在app.module.ts中引用
json和service
2 json文件格式
格式类似这样,根据实际需求决定。
[ { "id":"1", "name":"xiehan", "age":"24", "message":"测试json文件读取" }, { "id":"2", "name":"xiehan", "age":"24", "message":"测试json文件读取" }, { "id":"3", "name":"xiehan", "age":"24", "message":"测试json文件读取" }, { "id":"4", "name":"xiehan", "age":"24", "message":"测试json文件读取" }]
登录后复制
3 service
import {Injectable} from '@angular/core';import {Observable} from 'rxjs/Observable';import {Http, Response} from '@angular/http';import "rxjs/add/operator/map";@Injectable()export class DemoService { constructor(private httpService: Http){ } // 网络接口请求 getHomeInfo(): Observable { return this.httpService.request('http://jsonplaceholder.typicode.com/users') } // 本地json文件请求 getRequestContact(){ return this.httpService.get("assets/json/message.json") }}
登录后复制
4 数据显示
1 网络接口请求
//home.tsimport {ChangeDetectorRef, Component} from '@angular/core';import { NavController } from 'ionic-angular';import {DemoService} from "../../services/demo.service";@Component({ selector: 'page-home', templateUrl: 'home.html'})export class HomePage { // 接收数据用 listData: Object; // 依赖注入 constructor(public navCtrl: NavController, private ref: ChangeDetectorRef, private demoService: DemoService,) { } ionViewDidLoad() { // 网络请求 this.getHomeInfo(); } getHomeInfo(){ this.demoService.getHomeInfo() .subscribe(res => { this.listData = res.json(); // 数据格式请看log console.log("listData------->",this.listData); this.ref.detectChanges(); }, error => { console.log(error); }); }} //home.html 首页 {{item?.name}}
登录后复制
效果图
2 本地json文件请求
service中已经写了getRequestContact()方法对本地json文件读取。
//contact.tsimport {ChangeDetectorRef, Component} from '@angular/core';import { NavController } from 'ionic-angular';import {DemoService} from "../../services/demo.service";@Component({ selector: 'page-contact', templateUrl: 'contact.html'})export class ContactPage { contactInfo=[]; constructor(public navCtrl: NavController, private demoService: DemoService, private ref: ChangeDetectorRef,) { } ionViewDidLoad() { // 网络请求 this.getRequestContact(); } getRequestContact(){ this.demoService.getRequestContact() .subscribe(res => { this.contactInfo = res.json(); console.log("contactInfo-->",this.contactInfo); this.ref.detectChanges(); }, error => { console.log(error); }); }}// contact.html 联系人姓名:{{item?.name}} 年龄:{{item?.age}} 信息:{{item?.message}}
登录后复制
效果图
三 总结
1.所有创建的page要在app.module.ts中引用;
2.service要在app.module.ts中引用;
相关推荐:
Angular4实现鼠标悬停3d倾斜效果实例分享
Angular4自制一个市县二级联动组件详解
Angular4中项目的准备和环境搭建操作
以上就是ionic3和Angular4实现接口请求及本地json文件读取实例的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2788324.html