XMPP: AngularJs + Strophe.js

2019-03-16 18:33发布

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.

3条回答
对你真心纯属浪费
2楼-- · 2019-03-16 18:56

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).

查看更多
▲ chillily
3楼-- · 2019-03-16 19:06

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
       }
   }
}

}

})
查看更多
forever°为你锁心
4楼-- · 2019-03-16 19:14

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.

查看更多
登录 后发表回答