ember.jssocket.ioember-model

Ember JS: Service - Get data from Socket.io


Is this an app appropriate way to get data into a Service?
This is what I'd like to have happen.

import Ember from 'ember';

export default Ember.Service.extend({
    model: (function() {
        var data = [];

        var socket = io.connect('http://localhost:8080');

        socket.on('posts', function (data) {
            data = data.posts;
            console.log(data);
        });

        return data;
    })()
});

Is there a proper way to go about this?
Is this an app appropriate way to get data into a Service.
File Location app/services/posts.js



Solution

  • I assume you want something like this:

    export default Ember.Service.extend({
        init() {
            const socket = io.connect('http://localhost:8080');
            socket.on('posts', data => {
                this.set('data', data.posts);
            });
        },
        data: null,
    });
    

    However you should know that data will first by null and then later update when the data from the socket arrives. The other way is to return a Promise, but with this solution you can use the socket to update your data later.