Quantcast
Channel: Jose Luis Monteagudo
Viewing all articles
Browse latest Browse all 13

Local Parse Server + Ionic2 tutorial

$
0
0

 

In this video we create a mobile application with Parse Server installed locally in our computer and with Ionic2.

Parse Server

Parse Server is a server that run on NodeJS, over Express server, and it stores the information in a MongoDB database. By default, Parse Server provides us many features that would be costly to implement by ourselves. Some of these features are users and roles management, realtime notifications, files uploads and management on the server, geo queries, push notifications, etc. Parse Server also provides us a dashboard that allows us to develop our APIs (classes) very easy.

These are the steps that we have to follow to have our Parse Server running:

$ git clone https://github.com/ParsePlatform/parse-server-example.git MyAppServer
$ npm install
$ npm start

 

Once we have cloned the repository, we have the server, that is the file index.js. We are going to include some lines of code to this file in order to setup the dashboard. But before this, we have to install the package parse-dashboard:

$ npm install parse-dashboard --save

 

Next, we are going to update index.js and we have to add the lines of code that I have highlighted with yellow color:

// Example express application adding the parse-server module to expose Parse
// compatible API routes.

var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var path = require('path');

var allowInsecureHTTP = false;


var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;

if (!databaseUri) {
  console.log('DATABASE_URI not specified, falling back to localhost.');
}

var api = new ParseServer({
  databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
  cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
  appId: process.env.APP_ID || 'placeId',
  masterKey: process.env.MASTER_KEY || 'secret', //Add your master key here. Keep it secret!
  serverURL: process.env.SERVER_URL || 'http://localhost:1337/api',  // Don't forget to change to https if needed
  liveQuery: {
    classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
  }
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey


var dashboard = new ParseDashboard({
  "apps": [
    {
      "serverURL": "http://localhost:1337/api",
      "appId": "placeId",
      "masterKey": "secret",
      "appName": "PlaceApp"
    }
  ]
}, allowInsecureHTTP);



var app = express();

// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));

// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/api';
app.use(mountPath, api);

// make the Parse Dashboard available at /dashboard
app.use('/dashboard', dashboard);


// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
  res.status(200).send('I dream of being a website.  Please star the parse-server repo on GitHub!');
});

// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
  res.sendFile(path.join(__dirname, '/public/test.html'));
});

var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
    console.log('Place Server running on port ' + port + '.');
});

// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);

Once our server is finished, we can access the dashboard and start designing our classes.

Ionic2

We have to create an Ionic2 app, and next we have to create a provider that will get the information from our server. This is the code of our provider:

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class PlaceService {

  url: string = 'http://localhost:1337/api/classes/Place';
  headers: Headers = new Headers();

  constructor(public http: Http) {
    this.headers.append('Content-Type', 'application/json');
    this.headers.append('X-Parse-Application-Id', 'placeId');
  }

  findAll() {
    return this.http.get(this.url, {headers: this.headers}).map(response => response.json().results);
  }

}

 

In the constructor of our page we have to call to our provider to get the information from the server:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { PlaceService } from '../../providers/place';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  places: any[];

  constructor(public navCtrl: NavController, public placeService: PlaceService) {
    this.placeService.findAll().subscribe(places => this.places = places);  
  }

}

 

Finally, we have to update our template to display the information that we got through the provider:

<ion-header>
  <ion-navbar>
    <ion-title>Places</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <ion-card *ngFor="let place of places">
    <img src="{{place.image_url}}"/>
    <ion-card-content>
      <ion-card-title>
        {{place.title}}
      </ion-card-title>
      <p>{{place.description}}</p>
    </ion-card-content>
    <ion-row>
      <ion-col>
        <button ion-button icon-left clear small>
          <ion-icon name="calendar"></ion-icon>
          <div>{{place.createdAt | date}}</div>
        </button>
      </ion-col>
    </ion-row>    
  </ion-card>  

</ion-content>

 

 

The post Local Parse Server + Ionic2 tutorial appeared first on Jose Luis Monteagudo.


Viewing all articles
Browse latest Browse all 13

Trending Articles