我目前正在使用角度流星建立一个使用meteor和angularJS的应用程序。我目前正在问自己,如何正确处理订阅。我目前的做法是:
有更高效的方法吗?
profileRoutes.js:
function profileRoutes($stateProvider, ResolverProvider) {
$stateProvider
.state('user.profile', {
url: '/:username/profile',
resolve: _.extend(
{
$title: ['$stateParams', function($sp) {
return $sp.username + "'s Profil";
}]
},
ResolverProvider.waitForMedia(),
ResolverProvider.waitForUsers()
),
abstract: true,
views: {
'main': {
controller: 'UserProfileController',
templateUrl: 'client/components/users/profile.html'
}
}
});
}
angular
.module('myApp')
.config(profileRoutes);
resolver.js
function ResolverProvider() {
/**
* _stopIfSubscribed
*
* Checks if a subscription for that publication is already present and stops it.
* @param publicationName
* @private
*/
function _stopIfSubscribed(publicationName) {
_.forEach(_.get(Meteor, 'default_connection._subscriptions'), (handle) => {
if(_.get(handle, 'name') === publicationName && handle.stop) {
handle.stop();
}
});
}
/**
* waitForUsers
*
* Returns resolvers for waiting on my own and all other users
* Does not require a user
* @returns {{meSubscription: *[], usersSubscription: *[]}}
*/
this.waitForUsers = () => {
return {
"meSubscription": ['$meteor', function ($meteor) {
return $meteor.waitForUser();
}],
"usersSubscription": ['$meteor', function ($meteor) {
_stopIfSubscribed('allUsers');
return $meteor.subscribe('allUsers');
}]
};
};
/**
* waitForMedia
*
* Returns resolvers for waiting on galleries and media
* @returns {{mediaSubscription: *[], gallerySubscription: *[]}}
*/
this.waitForMedia = () => {
return {
"mediaSubscription": ['$meteor', function ($meteor) {
_stopIfSubscribed('media');
return $meteor.subscribe('media');
}],
"gallerySubscription": ['$meteor', function ($meteor) {
_stopIfSubscribed('galleries');
return $meteor.subscribe('galleries');
}]
};
};
}