Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Ionic, Stack Overflow

Connect to MongoDB remote server with Ionic

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m currently #1 in the top All time answerers list.

I answered this question by user Antifa:

I’m trying to develop an application in phonegap/ionic and I want to use a remote database to store my data. I want to use MongoDB. I already tried lots of ways such as this quick start guide.

By using this I can connect to DB but this is pure node.js and the require() function cannot be recognized when I try to add this code to an ionic starter app. Maybe require is not supported in ionic

Is there a way that can achieve it in Ionic?

Please let me know if you want some more information.

My answer was:

The thing is; you can’t connect Ionic to MongoDB directly. No, there’s not workaround, no magic involved, it’s just not the way this is supposed to work. Ionic works on top of Angular and Angular is a frontend framework.

However, the way you should do it is that you basically create a (RESTful) API on your server side.

Most likely this will be made with Node.js which will talk directly to MongoDB and query it. A framework very well suited for this (you actually may be using it already) is Express.

After you write your (RESTful) API then you can consume it through your services in Angular by using Angular’s $resource object.

Sure, this is not a step by step answer, and it seems you’re just starting in this area, so you have some learning do to on your part (REST, RESTful, $resource, services…), but I wish you good luck and if you’ll have any more specific questions, don’t hesitate to ask them.

https://twitter.com/HitmanHR/status/684267579976904704

Ionic, Stack Overflow

How to run Ionic serve permanently?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

I answered this question by user Santhosh Aineri:

I am using Ionic framework for one application. The code is on a linux server. I am running the application using ionic serve command through putty.

But, the problem is if I close the putty the application is stopped. Is there any way to run the ionic serve permanently as a daemon process?

My answer was:

I’m suspecting you’re trying to do this because you want to serve your Ionic app as a web app, correct?

In that case – you don’t have to run ionic serve permanently. All you have to do is take all the code from the www folder and place it in the http folder (or any other which is valid for your system) of your web server.

So, basically, spin up apache (or nginx) and serve the code from the Ionic’s www folder. Basically, ionic serve command does the same thing – it spins up a local web server and serves the content from the www folder. It does that for faster local testing.

You can take a look at this SO question for more info on how to deploy Ionic as a website.

How to run #Ionic #serve #permanently? https://t.co/7mbxGdSHFi

— Nikola Brežnjak (@HitmanHR) December 29, 2015

Stack Overflow

I reached 5k rep on StackOverflow and this is how it helped me

Yippee, my milestone has finally been reached; I went over the magical 5000 reputation on StackOverflow.

so5k

This currently places me in the top 4% this year, and in the top 2% in my country.

notBad

At the beginning, I was asking way more questions than giving answers, but that leveled out and recently I surpassed the number of questions (138) with the number of answers (147).

My current top 5+1 questions by number of upvotes:

(61) What is disableSelection used for in jQuery sortable?
(39) How to replace text between quotes in vi
(18) Serialize form not working in jQuery
(15) Add three dots in a multiline span
(14) PHP function to evaluate string like “2-1” as arithmetic 2-1=1
(12) jQuery Themeroller Gallery for Mobile

My current top 5+1 answers by number of upvotes:

(19) jQuery: select an element’s class and id at the same time?
(18) How to open a link new tab with print command?
(13) Linking using relative path on Github README.md
(7) Google MAP API Uncaught TypeError: Cannot read property ‘offsetWidth’ of null
(6) jQueryMobile data-dismissible in version 1.2
(6) What’s the difference between “ionic build” and “ionic prepare”?

For these questions I got the golden Famous Question badge (question with 10,000+ views):

  • Wait for images to load and then execute all other code
  • jQuery datatables plugin too slow – need a replacement
  • jQuery Mobile changePage with swipe transition
  • PHP function to evaluate string like “2-1” as arithmetic 2-1=1
  • Add three dots in a multiline span
  • Serialize form not working in jQuery
  • What is disableSelection used for in jQuery sortable?
  • How to turn off php safe mode in plesk 10? [closed]

The tags I’m most active in are ionic, ionic-framework, jquery, php, html, javascript, cordova, and 211 more.

In the question on meta.StackOverflow about how did StackOverlow help me, my answer was:

StackOverflow helped me a lot. Let me elaborate on this: currently, according to my upvotes, it helped me exactly 3,630 times a lot. Imagine that, learning 2.5 new useful things on average each day for four years now. And all that for free. Pro bono. Only upvote and (optionally) a kind word required.Priceless!

Also, more specifically, it helped me 133 times when I asked my own question (surprisingly, only 4 of them remained unanswered so far).

My experience with StackOverflow was very positive from the start (something I’ll elaborate a bit more below) – it was my first few weeks on a “test period” for a new job and I couldn’t solve one thing. They said it would be tricky and I sort of hoped that if I get it done quickly I’ll get some recognition. I did my fair share of googling and looking around the site (I knew about SO at that time already, but just haven’t asked any questions yet) and since I didn’t find any related question I finally decided to post. Not surprisingly, I got the answer in a matter of minutes. Sure enough, I did get permanently employed after that (and few other small tasks that I had to do on top of that).

See, I would like to emphasize on a way that I asked my first question, by repeating that I’ve googled quite a lot and searched through existing SO questions. Now, we who are around here a bit longer know what started to happen. New users started to come and, well, the quality of questions was not on a given level. And, that’s why it hurts me to see quite a lot of people shitting on StackOverflow (yeah, we know who they are – simple google search will turn out quite a few posts), but if we would just be honest and acknowledge the fact that it somehow seems that these days everyone wants something “out of the box – give me the codez plz”, without ever doing the research them self. What’s the learning value in that, I honestly don’t know.

Anyways, fast forward 4 years, I’m still loving it. Somewhere along the lines of using StackOverflow daily, I’ve grown as a developer and turned from the one who asks questions to someone who tends to contribute back to this wonderful community by giving answers. And, just yesterday I’ve “set the record straight” and leveled the number of my questions with the number of my answers. In the future I hope to help even more.

As for other opportunities StackOverflow provided me, I can only say countless. I don’t have a huge rep, but nevertheless I’ve gotten into an invite only programming site thanks to my SO profile. Also, I’ve gotten few requests to write a book, be a technical reviewer, and I get a lot of clicks from SO tomy blog. It seems a bit cocky to say, but people do tend to look at you differently when you say you have a somewhat fairly large amount of rep on SO. For me, it’s some kind of a badge of honor, to be honest 🙂

All in all – thank you StackOverflow.

See you at 20k! smileyGlasses

I reached 5k rep on #StackOverflow and this is how it #helped me https://t.co/A7xnWVOzkq pic.twitter.com/ZqiDFCyy7z

— Nikola Brežnjak (@HitmanHR) December 16, 2015

Stack Overflow

Include an object defined outside Angular ecosystem into a factory

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

I asked this question myself:

We’re having an argument, which I hope you guys will help resolve.

Say I have a simple factory defined like this:

angular.module('myModule', [])

.factory('Fact', function() {
    var Fact = function() {
        var that = {};

        that.var1 = [];
        that.var2 = [];

        return that;
    };

    var fact = {
        get: function() {
            return Fact();
        }
    };

    return fact;
});

I found out that this code will be working if I write it like this:

angular.module('myModule', [])

.factory('Fact', function() {
    var fact = {
        get: function() {
            return Fact();
        }
    };

    return fact;
});


var Fact = function() {
    var that = {};

    that.var1 = [];
    that.var2 = [];

    return that;
};

Namely, I can take this code of the object Fact and put it in some other plain .js file, include it before the Angular one (in index.html file) and this “would work”.

However, I’m trying to resolve an argument that this approach is not good (well, not an Angular approach at that) because then this Fact is “laying around on the global scope”, which is not good.

In which circumstances would you say that this is/isn’t a good solution?

Is there a way to include a “nonAngular” code (simple JavaScript code written in some .js file) into the Angular factory?

I accepted the answer from user Dan Prince:

Between factories, services, providers, constants and values, there’s not really a good reason to have any code outside of Angular’s constructs unless it’s third party code.

If it is, you won’t have control over the way that the library, framework, etc registers itself. It might use the global scope, alternatively, it might provide a module export.

Where possible, the cleanest and safest way to include third party code inside Angular is with a build-step using a module bundler.

For instance, I want to use the hypothetical package foojs from inside Angular using browserify:

Install the package with npm

npm install --save foojs

Then use it like this.

var foojs = require('foojs');

var app = angular.app('myapp')

app.service('myservice', function() {
  // here we can use foojs safely
});

You can also achieve similar things with WebPack.

The reason this is safer is because after the build step, all the modules will be wrapped inside a function that protects the global scope.

If you aren’t able to use a module bundler, then the only option is to use the global scope and allow the third party code to bind onto the window object.

https://twitter.com/HitmanHR/status/676654486115454976

Ionic, Stack Overflow

How to deploy Ionic as a website?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

edit: As of version 1.2 Ionic is officially saying that you are free to deploy Ionic as a website.

I answered this question by user Ayush Chordia:

I have created an ionic app and want to deploy it as a website. What’s the best way to deploy it on a custom domain ? I was thinking of using azure web app to host the ionic app. All the documentation refers to use it as hybrid app for IOS and Android. But at this point we are only interested for it to function as a website.

In my answer I disagreed with this one:

As I stated in the comment to the only provided answer – I disagree.

If you’re not using any Cordova plugins then there is no problem (if you really wish to) to upload the contents of the www folder to your server, and woila – you’ll have the same app.

However, it is important to note that Ionic never intended for such a use, and the users of your “website” will have to have a newest browser in order to see the “website” correctly (not broken down due to some feature that Ionic is using in either CSS or HTML that some older browsers do not support).

You can see such example here: http://nikola-dev.com/IonicCalculator/mobile.html, and you can take a look at the tutorial with step by step on how to recreate the application. I literally took out the contents of the www folder and put it on the web server, and as you can see it works.

https://twitter.com/HitmanHR/status/674121400911863808

Ionic, Stack Overflow

ionic plugin add phonegap-plugin-push results in a 404 Not Found Error

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

I actually asked this question myself:

I was following the official (and rather great) docs over at Ionic for how to get started with push notifications.

However, once the instructions said to install the phonegap-plugin-push plugin, I received the following error:

nikola@Nikolas-Mini ~/Desktop/ionicTesting/ionicPush
> ionic plugin add phonegap-plugin-push
Error: 404 Not Found: phonegap-plugin-push
at RegClient.<anonymous> (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:304:14)
at Request._callback (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/npm-registry-client/lib/request.js:246:65)
at Request.self.callback (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/request/request.js:236:22)
at Request.emit (events.js:110:17)
at Request.<anonymous> (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/request/request.js:1142:14)
at Request.emit (events.js:129:20)
at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/request/request.js:1096:12)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)

Anyone has an idea of why? I tried with cordova instead ionic but I get the same error.

Also, I managed to find the answer myself:

After quite some searching I stumbled upon an official blog post, Cordova is moving their plugins to npm.

So, finally, I installed it easily now with npm:

npm install phonegap-plugin-push

https://twitter.com/HitmanHR/status/671596248764428289

Ionic, Stack Overflow

Firebase $authWithOAuthRedirect doesn’t call $onAuth without page refresh

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

I actually asked this question myself:

I have a simple Firebase Facebook OAuth login set like below by following the official tutorial for the Ionic Firebase Facebook login.

The problem is that once I click on the login with Facebook button, I get redirected to Facebook, I log in, and I get redirected back to my app. However, the problem is that I stay in the login page. Strange thing is that if I physically refresh my browser (testing with ionic serve) by pressing F5 the onAuth triggers and I get redirected to the Items page. If I don’t refresh the browser, onAuthdoesn’t get called.

Did someone have this issue? How did you solve it?

Please note that yes, I did my research (and am slightly starting to lose it), but can’t get it to work. I searched SO, tried with $timeout from google groups, tried to call $scope.$apply(), but all to no avail – so please help me figure out where I’m doing it wrong?

.controller('AppCtrl', function($scope, Items, Auth, $state, $ionicHistory) {
    $scope.login = function(provider) {
        Auth.$authWithOAuthRedirect(provider).then(function(authData) {

        }).catch(function(error) {
            if (error.code === "TRANSPORT_UNAVAILABLE") {
                Auth.$authWithOAuthPopup(provider).then(function(authData) {
                    
                });
            } else {
                console.log(error);
            }
        });
    };

    $scope.logout = function() {
        Auth.$unauth();
        $scope.authData = null;

        $window.location.reload(true);
    };

    Auth.$onAuth(function(authData) {
        if (authData === null) {
            console.log("Not logged in yet");
            $state.go('app.login');
        } else {
            console.log("Logged in as", authData.uid);
            
            $ionicHistory.nextViewOptions({
                disableBack: true
              });
            $state.go('app.items');
        }
        $scope.authData = authData; // This will display the user's name in our view
    });
})
<ion-view view-title="Members area">
    <ion-content padding="true">
        <div ng-if="!authData">
            <button class="button button-positive button-block" ng-click="login('facebook')">Log In with Facebook</button>  
        </div>       
        
        <div ng-if="authData.facebook">
            <div class="card">
                <div class="item item-text-wrap">Hello {{authData.facebook.displayName}}!</div>                
            </div>

            <button class="button button-assertive button-block" ng-click="logout()">Log out</button>
        </div>        

    </ion-content>
</ion-view>

edit: I sort of solved it by using $timeout:

$timeout(function(){
    Auth.$onAuth(function(authData) {
        if (authData === null) {
            console.log("Not logged in yet");
            $state.go('app.login');
        } else {
            console.log("Logged in as", authData.uid);

            $ionicHistory.nextViewOptions({
                disableBack: true
              });
            $state.go('app.items');
        }
        $scope.authData = authData; // This will display the user's name in our view
    });
}, 3000);

However, this just feels wrong (mildly put), and there has to be a better way, so please suggest one. Also, I noticed that the whopping 3second delay is barely enough (few of the resources I found suggested 500ms would be enough, but in my case, that’s not the case).

Answer, from user mhartington, was:

Posted on the github issues, but will reply here as well.

This only happens in the browser using $authWithOAuthRedirect. The example was intended for cordova apps, so this really shouldn’t be an issue.

But if you really need it, you could just skip the redirect and use a popup.

Auth.$authWithOAuthPopup(authMethod).then(function(authData) {
      console.dir(authData);
    });

https://twitter.com/HitmanHR/status/671222279121076224

Ionic, Stack Overflow

Use navigator.geolocation or $cordovaGeolocation in Ionic

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

I actually asked this question myself:

Since I basically can get the same info with both approaches, I’m wondering which is the preferred one and what are the advantages using one over the other?

Answer, from user Mudasser Ajaz, was:

$cordovaGeolocation is angular wrapper over plain javascript plugin, developed by ionic. Now question is why ngCordova was introduced,in simple words to deal it as plugin service as module and inject plugin wrapper as dependency to only particular controller or service.
On Pratical level, cordova developers were having issues with plugins on angular project. One simple issue was that $scope does not get updated sometimes in simple plugins callback.
Quoting from ionic blog post :

The services support promises to make it easier to deal with their asynchronous nature and ensure scope data is properly updated

https://twitter.com/HitmanHR/status/671057737669832705

Stack Overflow

How to get nested object property with pluck in Lodash

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

This Lodash question was actually asked by myself:

I have an array of objects like this:

var characters = [
    { 'name': 'barney',  'age': 36, 'salary':{'amount': 10} },
    { 'name': 'fred',    'age': 40, 'salary':{'amount': 20} },
    { 'name': 'pebbles', 'age': 1,  'salary':{'amount': 30} }
];

I want to get the salary amounts into an array. I managed to do it by chaining two pluck functions, like this:

var salaries = _(characters)
  .pluck('salary')
  .pluck('amount')
  .value();

console.log(salaries); //[10, 20, 30]

Is there a way to do this by using only one pluck? Is there a better way with some other function in lodash?

The answer, from user thefourtheye, was:

You can just give the path to be used as a string, like this

console.log(_(characters).pluck('salary.amount').value())
// [ 10, 20, 30 ]

Or use it directly

console.log(_.pluck(characters, 'salary.amount'));
// [ 10, 20, 30 ]

https://twitter.com/HitmanHR/status/670237244695977984

Ionic, Stack Overflow

How to design a two column button in Ionic framework

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. I’m in the top All time answerers list.

I actually asked this question myself:

What I would like to achieve is this:

enter image description here

Surely, I went through the button documentation, but it seems nothing similar is there. So, I would appreciate some pointing in the right direction (codepen with a basic example would be most awesome).

So, ideally, this would be one button tag where I would be able to pass two variables (one which would appear on the left and one on the right). This does smell like a job for a Angular directive, though I haven’t fiddled with it too much just yet so a friendly nudge in the right direction would be appreciated.

Answer from Malek Hijazi was pointing out to use the ButtonBar component, but I already knew about it and it wasn’t what I needed. Finally, I managed to answer this question myself after some fiddling with it:

What I ended up doing in the end was this: I created a div with a class button and then inside it I created additional two div‘s with custom classes.

How this looks like on CodePen:

And, the code below:

.leftButtonSide {
    width: 50%;
    float: left;
    color: #000;
}

.rightButtonSide {
    width: 50%;
    float: left;
    background: #F2F2F2;
    color: #000;
    border-radius: 2px;
}
<div ng-repeat="d in data" class="button button-positive-outline">
    <div class="leftButtonSide">2</div>
    <div class="rightButtonSide">2,00</div>
</div>

True, for the exact same look you would have to play a bit with CSS. I ended up with this in the end:

Hope this helps someone too!

https://twitter.com/HitmanHR/status/669836667893768192

Page 2 of 9«1234»...Last »

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak