技术控

    今日:136| 主题:49552
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Working with Data: Services vs. Nav Params

[复制链接]
南歌子 发表于 2016-10-6 06:39:20
149 4

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Gotta pass data around our apps. Pretty much unavoidable. Why? Because apps are made up of a whole bunch of views and user interactions and…stuff, none of which tend to exist in isolation. Whether we’re talking about data pulled in via a REST API, collected from a user input, generated client-side, or whatever else, it is often the case that we’ll need to use it in more than one place to create the types of rich experiences users have come to expect from mobile. At the same time, resources like data usage and battery life are limited on mobile, so we want to keep things like network requests and computation to a minimum whenever possible. Keep it DRY (don’t repeat yourself), as the old saying goes.
  In today’s blog post, we’ll take a look at two ways to do this in an Ionic 2 app: Angular services and Ionic nav params.  
  Using an Angular Service

  Let’s start with the slightly more complicated but more robust option of building an Angular service. Services allow us to create a shared instance of a class that we can inject into any component of our app via the Angular 2 dependency injection system.
  Here’s a quick example involving ice cream, since sharing ice cream is awesome.
  First, the skeleton of a service. All we need is to import Angular’s    Injectableand a basic class declaration:  
  1. import { Injectable } from [email protected]
复制代码
/core'; @Injectable() export class IceCreamService { constructor() {} }
  If you want to generate this boilerplate automatically, try using the    generatecommand in the Ionic CLI, which will create the above plus a little extra for you in    /app/providers/ice-cream-service/ice-cream-service.ts:  
  ionic generate provider ice-cream-service
  Syntactically, the only thing that makes this different from an Angular component is the use of the    @Injectable()rather than the    @Componentdecorator above the    exportstatement. This tells the Angular compiler that this class is available for use in Angular’s dependency injection system.  
  Next, let’s add some logic to the service:
  1. export class IceCreamService {
  2.   hadIceCream: boolean = false;
  3.   constructor() {}
  4.   getIceCream() {
  5.     hadIceCream = true;
  6.     return 'mmmm... ice cream';   
  7.   }
  8. }
复制代码
Pretty simple. We have an member variable that tells us if the user has had ice cream already, and a    getIceCream()function. Next, let’s use it in a component by doing three things:  
  
       
  • importing the service   
  • adding the provider for the service in the component declaration   
  • creating an instance in the component’s constructor  
  1. import { Component } from [email protected]
复制代码
/core'; import { NavController } from 'ionic-angular'; //import the class from the service import { IceCreamService } from '../../providers/ice-cream-service/ice-cream-service'; //the class name of the service is the provider @Component({ templateUrl: 'build/pages/home/home.html', providers: [IceCreamService] }) export class IceCreamPage { //create an instance of the service constructor(public iceCreamService: IceCreamService, public navCtrl: NavController) { } }
  Now, all we need to do is use the Valuable and Important data the service provides to our component about whether or not the user has already gotten their fair (and very generous, I assure you) allotment of ice cream:
  1. export class IceCreamPage {
  2.   message: string = "Ice cream. It's Good and You Want It.";
  3.   constructor(public iceCreamService: IceCreamService, public navCtrl: NavController) {}
  4.   getIceCream() {
  5.     if (!this.iceCreamService.iceCreamRedeemed) {
  6.       this.message = this.iceCreamService.getIceCream();
  7.     } else {
  8.       this.message = 'Stop hogging all the ice cream =(';
  9.     }
  10.   }
  11. }
复制代码
Notice how the component can access any public member of the service. In this case, we use the    iceCreamRedeemedvariable in the conditional, as well as the    getIceCream()function. Better yet, this is a shared instance, so any component in our Ionic app will also have full and consistent access to the user’s status.  
  Using Ionic Nav Params

  Our service is neat, but I’ll admit it could be a little bit of overkill for something as simple as ice cream. On to nav params!
  Nav params is a feature of navigation in Ionic that allows us to pass a JSON object from one page to the next. Using our ice cream app, let’s imagine for a moment that we are going to navigate to our    IceCreamPagefrom a different view by using:  
  this.navCtrl.push(IceCreamPage)
  All we need to do to use nav params is pass a JSON object as the second argument of    push():  
  this.navCtrl.push(IceCreamPage, {status: true})
  To get this in our    IceCreamPage, we import Ionic’s    NavParamscomponent:  
  import { NavController, NavParams } from 'ionic-angular';
  Then create an instance of it in our constructor and call    get(key)to retrieve the value from the nav params object. In this case, we call    get('status'):  
  1. constructor(private _navCtrl: NavController, private _navParams: NavParams) {
  2.     if (!this.navParams.get('status')) {
  3.     this.message = 'Have some ice cream =)';
  4.   } else {
  5.     this.message = 'Stop hogging all the ice cream =(';
  6.   }
  7. }
复制代码
Descisions, Decisions

  Mobile app development, like life, is full of choices. Services and nav params are both good ways of moving data around our app, but how do we pick? The first thing to think about is where the data is going. If we are navigating from one view to the next with either Ionic’s    NavController.push()or    NavController.pop(), then nav params could be a good choice. It’s lightweight and easy to implement. Conceptually, it also makes it very easy to reason about how data is flowing between views in our app, since we are passing it off directly.  
  The next thing to consider is persistence. Will the data be needed in the future, or does it need to be used in more than one view of our app? If this is the case, a service is probably more appropriate. Since services create shared instances that can be injected into any view, they can ensure immutability and/or consistency. In short, we can easily ensure that the data will be the same everywhere it is used, since every component will be consuming the same data source.
  The important thing is that the ice cream is safe.
友荐云推荐




上一篇:What If a Company Consistently Says No to Open Sourcing Their Code?
下一篇:Windows小工具:LnkDown快捷方式加载Payload
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

华仔哈哈 发表于 2016-10-6 07:30:15
专业顶帖的!哈哈
回复 支持 反对

使用道具 举报

冯志生 发表于 2016-10-10 17:26:04
大学就是大概学学!
回复 支持 反对

使用道具 举报

Conley 发表于 2016-10-10 20:32:48
我也来顶一下..
回复 支持 反对

使用道具 举报

天巧 发表于 2016-10-11 04:08:19
洗洗更白白,顶顶更健康!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表