在我的下面的实现中,我尝试从ember-simple-auth-token
获取令牌,并使用URL,用于连接ActionCable:
...
export default Route.extend({
store: service(),
currentUser: service(),
session: service(),
cable: service(),
setupConsumer: on('init', function() {
let token = this.get('session.data.authenticated.jwt');
let consumer = this.get('cable')
.createConsumer(`wss://api.${config.APP.host}/cable?token=${token}`);
let channelMixin = Mixin.create({
received(data) {
this.get('store').pushPayload(data);
}
});
consumer.subscriptions.create({
channel: 'ChatroomsChannel'
}, channelMixin);
}),
...
});
这仅适用于第一次请求。我需要将它存储在cookie中吗?感谢。
答案 0 :(得分:1)
以下代码解决了我的问题:
import Route from 'ember-route';
import service from 'ember-service/inject';
import Mixin from 'ember-metal/mixin';
import config from 'apollo-enterprise/config/environment';
export default Route.extend({
session: service(),
cable: service(),
afterModel(model) {
this.get('session.store').restore().then((data) => {
let token = data.authenticated.jwt;
let consumer = this.get('cable')
.createConsumer(`wss://api.${config.APP.host}/cable?token=${token}`);
let channelMixin = Mixin.create({
store: service(),
received(data) {
this.get('store').pushPayload(data);
}
});
consumer.subscriptions.create({
channel: 'MessagesChannel',
chatroom_id: model.id
}, channelMixin);
});
},
setupController(controller) {
this._super(...arguments);
controller.set('message', {});
},
actions: {
sendMessage(params) {
let chatroom = this.controller.get('model');
let message = this.get('store').createRecord('message', params);
message.set('chatroom', chatroom);
message.save().then(() => {
this.controller.set('message', {});
});
}
}
});