I'm new to the angular 2 and nativescript. I would like to create application that can run on web and on mobile. I read that you can share code using this frameworks and just to switch templates, but there is no tutorials or documentation. So, if anyone could give me some directions for start, how can I do this.
Thanks!
tl;dr: Try not to put any platform specific or UI code in your services. These services can then be shared between platforms.
The first thing you need to understand is that in native views, you can't use the same markup (div, span, table etc.) as in normal browsers. So all your UI needs to be coded individually for web and mobile.
If you follow the best practices of Angular 2, you'd have divided your apps into components, directives and services. Ideally, services are where most of the logic of your app goes. They should handle http, caching, common helper methods, global constants etc.
You can reuse these services with minor to no changes between web and mobile if they don't contain any platform specific code. For instance, the http
exposed by angular and nativescript-angular have the same api. So if you're doing something via http as service, and that service doesn't juggle any UI elements (it shouldn't), that service should work on both web and browser. You can share the directory of services between web and mobile projects and override anything you want to customise for platform.
Example: Suppose you want to get a list of users from backend and display them as list. Ideally, you'll have a User
service which has a get
method returning promise of a json list of users from BE.
ListView
, import the User
service and use the promise from get
method to populate it.<li>
in its template.It's all about keeping your services as free of platform specific code as you can.
Hope this helps you get started on how to structure your application for maximum code reuse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With