简体   繁体   中英

SailsJS - Angular2 - Resourceful Pub/Sub

Don't see much of anything on the web that covers Angular2 and SailsJS Resourceful Pub/Sub scenarios. I am trying to watch a model for new records and display them in my Angular2 app. I am using the angular2-sails module. The code below successfully gets the data into my angular app but requires a page refresh to get the new data. The goal is to get the data in real-time without a page refresh.

Sails Controller Actions:

  newCall: function(req, res) {

    if (!req.isSocket)
      return res.badRequest;

    Call.create({
      payload: req.body
    })
    .exec(function (err, newCall){
      if (err) return res.negotiate(err);
      Call.publishCreate(newCall);
      res.ok(newCall);
    });
  },

getCalls: function(req, res) {
    Call.find()
    .then(function(calls) {
        Call.watch(req.socket);
        console.log(req.socket.id + ' is now watching for changes to Calls model');
        res.send(calls);
    })
    .catch(function(err) {
        console.log(err);
    });
}

Angular2 Component:

  ngOnInit() {
    let sails = this._sailsService;
    sails.connect("http://localhost:1337")
    sails.get('/socket/getCalls')
    .subscribe(
      (resData) => { this.calls = resData.data.length},
      (error) => { console.log("oooops, error occured") },
      () => { console.log("we are finished") }
    )
  }

Simply had to .on("model") that I am .publishCreate ing

 sails.on("call")
  .subscribe(
  (resData) => {
    this.call_count = this.call_count + 1;
    this.calls_realtime.push(resData.data);
  },
  (error) => { console.log("Error") },
  () => { console.log("End") }
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM