XMPP: AngularJs + Strophe.js

All we need is an easy explanation of the problem, so here it is.

I have a basic XMPP client working on strophe.js.

On login I create handlers such as

connect = new Strophe.Connection('http://localhost/http-bind');
...
...

    connect.addHandler(on_message, null, "message", "chat");
    connect.addHandler(on_presence, null, "presence");

...
...

and then I “listen” to those

function on_presence(presence) {
// handling presence
}

function on_message(presence) {
// handling presence
}

So I am trying to “convert” it into AngularJS. The first part is pretty straight forward. I have a controller which handles the login part just fine:

angular.module('app').controller('loginCtrl', function($scope) {
connect = new Strophe.Connection('http://website.com/http-bind');

connect.connect(data.jid, data.password, function (status) {
  if (status === Strophe.Status.CONNECTED) {
    connect.addHandler(on_message, null, "message", "chat");
    connect.addHandler(on_presence, null, "presence");
  }
}
})

But how do I actually begin listening to those events (on_message, on_presence) in the context of angular across all the controllers I have.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Wrap Strophe in an Angular Service. Angular Services are meant to be use as singletons, so you will be able to instantiate the Strophe Service once, and use it everywhere (using Dependency Injection).

Method 2

As suggested above (or bellow) I wrapped strophe in a service so my login “mechanism” looks like this:

.controller('loginCtrl', function(xmppAuth) {

    xmppAuth.auth(login, password);

})

any my service:

.service('xmppAuth', function() {

return {

auth: function(login, password) {
   connect = new Strophe.Connection('http://mydomain.net/http-bind');
   connect.connect(login, password, function (status) {
       if (status === Strophe.Status.CONNECTED) {
           // we are in, addHandlers and stuff
       }
   }
}

}

})

Method 3

Or may be you can create a module for Strophe and then include the module in your app, and then include strophe as a variable where ever you want to use it.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply