urigo / meteor-rxjs Goto Github PK
View Code? Open in Web Editor NEWExposing Mongo Cursor as RxJS Observable
License: MIT License
Exposing Mongo Cursor as RxJS Observable
License: MIT License
Hi,
To run arbitrary code when a subscription changes I've always used the snippet at readiness ?
It leverages the fact that "ready()" is a reactive data source.
How do I achieve the same with meteor-rxjs ?
Thanks,
Raffaele
I am using https://github.com/meteor/validated-method for creating and calling Meteor methods. Is it possible to convert ValidatedMethod using this package?
Meteor package "allow-deny" in file allow-deny.js:162 throws sync error before creating observer in observers array in https://github.com/Urigo/meteor-rxjs/blob/master/src/ObservableCollection.ts#L132 line.
And console silent....
For example run code on client: Tags.update({key: tag}, {$inc: {count: inc}}, {upsert: true});
Branch | Build failing π¨ |
---|---|
Dependency | zone.js |
Current Version | 0.7.6 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As zone.js is βonlyβ a devDependency of this project it might not break production or downstream projects, but βonlyβ your build or test tools β preventing new deploys or publishes.
I recommend you give this issue a high priority. Iβm sure you can resolve this πͺ
The new version differs by 14 commits .
8af21b5
chore: release v0.7.7
808f6fd
feat: allow tasks to be canceled and rescheduled on different zone in a zone delegate
47962df
fix(patch): check timer patch return undefined (#628)
f300658
docs(core): add standard api document (#625)
35aeb68
docs(core): remove old example, update counting example with new API (#624)
6731ad0
feat: make fetch() zone-aware without triggering extra requests or uncatchable errors. (#622)
d6772e2
refactor(node): patch nextTick with more general patchMicroTask method (#617)
9818139
feat: add Zone.root api (#601)
6d31734
feat(electron/nw): fix #533, in electron/nw.js, we may need to patch both browser API and nodejs API, so we need a zone-mix.js to contains both patched API.
ac7b046
feat(promise a+) fix #591, make ZoneAwarePromise pass promise a+ test (#592)
9e81037
fix(node): patch crypto as macroTask and add test cases for crypto, remove http patch (#612)
7665e5a
test(fix): fix flaky test setInterval in android 4.4 (#611)
437ab4e
docs: Document non standard web apis (#610)
33d0d8d
fix(minification): fix #607 to change catch variable name to error/err (#609)
See the full diff.
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
Thank you for this package!
Are there any instruction, how to use meteor-rxjs with GroundDB 2?
This will be useful for cordova apps
Or are there any other mechanism we can cache in localstorage the result from observable and load from it when there is no internet access?
maybe I am misunderstanding how find should with with RXJS in Meteor.
if I have this on the client
Models
find(type): Observable<any[]> {
return this.Models.find({});
}
constructor(){
MeteorObservable.subscribe('testCollection').subscribe();
this.Models = new MongoObservable.Collection<any>('testPublisher', {idGeneration: 'MONGO'});
}
and this on the server
Meteor.publish('testPublisher', function () {
this.added('testCollection', 'testId', {doc: []});
this.ready();
this.changed('testCollection', 'testId', {doc: [{test:'test'}]});
})
shouldn't the 'this.changed' trigger the find results to return the updated model in the find query? However, I am only ever receiving the initial model from 'this.added'.
Thanks
The docstring says:
@returns {Observable<{numberAffected, insertedId}>} Observable which completes with an * Object that contain the keys numberAffected and insertedId.
However the return value is let obs = this._createObservable<number>(observers);
So either there is a bug in the documentation or in the implementation.
Edit:
So The original Meteor Collection.upsert() function actually returns {numberAffected, insertedId}
directly instead of in the callback.
Hey Guys,
I'm getting:
Property 'added' is missing in type 'Subscription'
Property 'unsubscribe' does not exist on type 'Subscription'
notifications in my console. Is there anything missing in my typing? I added
/// <reference types="meteor-typings" />
Thanks Dominic
Observables do not update on client using angular 2.4 and rxjs greater than 5.0.1. Has anyone else experienced this issue?
Not Working code:
// things: Observable<THING[]> // type of things is array of THING in class definition.
// in template <div *ngFor="let thing of things | async">
MeteorObservable.autorun().zone().subscribe(() => {
this.things = Things
.find({ someIdOfSubDocument: changedProp.currentValue._id })
.zone();
});
});
Only possible solution I found is below:
//things: THING[]; // type of things is array of THING in class definition.
// in template <div *ngFor="let thing of things">
MeteorObservable.autorun().zone().subscribe(() => {
Things
.find({ someIdOfSubDocument: changedProp.currentValue._id })
.zone()
.subscribe((quotes) => {
this.ngZone.run(() => {
this.things = quotes;
});
});
});
Why the things: Observable<THING[]> is not updating the view upon changes from the server, however, it is updating only on the new records.
When I don't separate meteor from the client I access to multiple databases using
var database = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: database });
There is any way to access multiple databases from the client using meteor-build-client?
I have to create methods, or there is an easier way?
Branch | Build failing π¨ |
---|---|
Dependency | babel-runtime |
Current Version | 6.22.0 |
Type | peerDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As babel-runtime is βonlyβ a peerDependency of this project it might not break production or downstream projects, but βonlyβ your build or test tools β preventing new deploys or publishes.
I recommend you give this issue a high priority. Iβm sure you can resolve this πͺ
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
Hi,
I just wanna querying data (all checked (true and false) data are publish on client) by toggling checked variable but I get data just for the first time actually by initialization ( getData()
is also placed in ngOnInit()
wrapped by MeteorObservable.subscribe
) and never more by toggling. What Am I doing wrong ?
Thanks for any help
Michal
checked:boolean = false
getData(){
Tasks.find({checked: this.checked})
.map(tasks => tasks.length)
.subscribe(todoCount => console.log(todoCount));
}
Branch | Build failing π¨ |
---|---|
Dependency | @types/meteor |
Current Version | 1.3.31 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As @types/meteor is βonlyβ a devDependency of this project it might not break production or downstream projects, but βonlyβ your build or test tools β preventing new deploys or publishes.
I recommend you give this issue a high priority. Iβm sure you can resolve this πͺ
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
Let a MyItems observable collection be mapped as so:
export let MyItems = new MongoObservable.Collection<MyItem>(
new Mongo.Collection<MyItem>('myitem', { transform: (doc) => {
return new MyItem(doc);
}})
);
when I try to loop on the result of a find
MyItems.find().forEach(v => { console.log(v._id); });
I get the following error in the console:
Property '_id' does not exist on type 'MyItems[]'.
If I try to declare v as Myitem I would get
'(v: MyItem) => void' is not assignable to parameter of type '(value: MyItem[]) => void'.
Any idea what could be wrong ? I am not expecting MyItem[] but MyItem.
Typescript.d.ts was working before remapping my collections to MongoObservable's collections.
I was using SimpleSchema (https://github.com/aldeed/meteor-simple-schema) earlier with my Mongo.Collections. Now changing the class to extend from MongoObservable.Collection is breaking the application. I do not know how i can attach SimpleSchema with my collection. Any advice will be welcome.
Are there any plans to add Observable complete functionality?
Angular HTTP returns completed observables when returned from the server. Observables returned from meteor-rxjs are returned as not complete. Consequently, many features of rxjs are not usable such as concat, take, etc.. It would be ideal to provide a flag "option" to return completed observables..
this.http.get('/orders')
.subscribe(
data => this.orders = data,
error => console.log(error),
() => { alert('finished!'); } // <- this called with Angular http
);
Hi,
I'm facing an issue with findOne function.
Yes, when the subscription is not ready, the function return undefined.
Should we wait subscriptionReady for a findOne Operation?
Or I'm going in the wrong direction?
Let me know :)
Thank you
Hi guys,
I like this library but the IDE don't allow me to import MongoObservable
automatically, like this:
import {MongoObservable} from 'meteor-rxjs';
In the same project, other class work fine.
Any suggestions?
Hi there,
I am struggling to find a way to use the last() rxjs operator on some MongoObservable.Collection like this:
import 'rxjs/add/operator/last';
const NewsfeedCollection = new MongoObservable.Collection<NewsfeedCollectionModel>("newsfeed");
NewsfeedCollection.find({})
.last()
.subscribe(console.log);
There is no results logged, if some of you have met the same issue
I'm getting an exception and don't understand why. The sample code is cut down from the original, but the line in question starts let subscription=
. This code is within a method so only occurs on the server side.
The failing line within Meteor subscribe():
return Meteor.subscribe.apply(Meteor, [name].concat(args.concat([{...
Here's the exception and traceback:
Exception while invoking method 'someMethod' TypeError: Cannot read property 'apply' of undefined
at subscribe (c:\Build\myapp\node_modules\meteor-rxjs\dist\bundles\index.umd.js:609:36)
at Observable._subscribe (c:\Build\myapp\node_modules\meteor-rxjs\dist\bundles\index.umd.js:628:30)
at ZoneOperator.call (c:\Build\myapp\node_modules\meteor-rxjs\dist\bundles\index.umd.js:695:23)
at Observable.subscribe (c:\Build\myapp\node_modules\rxjs\Observable.js:42:22)
Here's my code within a Meteor method:
let list = MyCollection.find(aselector);
let subscription= MeteorObservable.subscribe("publishedList, selector).zone().subscribe( () => {
list = MyCollection.find(selector);
let myArray = list.fetch();
let item: MyItem = myArray.length > 0? myArray[0]: null;
});
Hello,
I have been using MeteorObservable for a while (much better than Meteor.find). However, to get data from a publication (particularly one that takes an input variable to select results) I have to "subscribe to the publication", .subscribe to a MeteorObservable. On destroy, I have to unsubscribe to the publication and MeteorObservable. When desiring new results, I need to subscribe two times and unsubscribe two times. It would be nice if both of these could be combined, in which when subscribing to the MeteorObservable.find, I would also subscribe to a publication (that is generated) that would send the results to the client. Perhaps there is a better implementation pattern I am not aware of?
This is the flow:
For example:
obs.subscribe(cb1);
obs.next([1]); // cb1 called with [1]
obs.next([1,2]); // cb1 called with [1, 2]
obs.subscribe(cb2);
// cb2 will never called until the next time "obs.next(..)"
The current solution is to .publishReplay(1).refCount();
the Observable - this way a new subscribers will get the last value of the Observable upon new Subscription.
This is that happens when using this solution:
obs.subscribe(cb1);
obs.next([1]); // cb1 called with [1]
obs.next([1,2]); // cb1 called [1,2]
obs.subscribe(cb2); // cb2 called [1,2]
Hi,
If client is offline MeteorObservable.subscribe
won't fire and Collection.find()
inside of MeteorObservable.subscribe
won't fire too. How can I achieve that Collection.find()
will fire every time ? My goal is to get cached data from minimongo even if client is offline
e.g.
MeteorObservable.subscribe('posts').subscribe(()=>{
this.sub = Collection.find();
});
thanks
Best Regards
Michal
Anonymous collection is really helpful, I need it because I need reactivity for some data, but I don't need to save it in mongo db.
Is it possible to use it?
JIC as example of anonymous collection is the error management in discover meteor tutorial: http://es.discovermeteor.com/chapters/errors/
let collection = new Mongo.Collection('foo');
let observable = new MongoObservable.Collection(collection);
collection.applySchema(...); // with SimpleSchema package
So far it's
collection.attachSchema(...); // with SimpleSchema package
Hi
Example 1
this.autorun(h => {
this.subscribe('myCollection', this.filterQuery.get(), {limit: this.recordLimit.get()});
this.items= MyCollection.find(this.filterQuery.get(), {limit: this.recordLimit.get()});
Example 2 (1 line added at the end)
this.autorun(h => {
this.subscribe('myCollection', this.filterQuery.get(), {limit: this.recordLimit.get()});
this.items= MyCollection.find(this.filterQuery.get(), {limit: this.recordLimit.get()});
this.items.subscribe();
In both examples, ReactiveVars are running in an autorun
to update the subscription and collection cursor. this.items
is in both cases rendered with a ngFor .. | async
.
However, when I increase the limit value this.recordLimit.set(this.recordLimit.get() + 10)
, I notice that:
ngFor
.Is that normal subscribe()
has this kind of impact ?
Hey, I'm not able to get out the _id after I insert a new item to my meteor-db.
My code looks like this:
Server:
newItem() {
if (!this.userId)
throw new Meteor.Error('unauthorized', 'User must be logged-in to insert an item');
return Items.insert({ ownerId: this.userId, title: 'New Item' });
}
Client:
MeteorObservable.call('newItem').subscribe({
next: () => {
//get _id
},
error: (e: Error) => {
console.log("Error: " + e);
}
});
Can you please tell me how to get the _id
?
I also posted here: http://stackoverflow.com/questions/41040730/ionic2-meteor-get-id-of-new-inserted-item
I have a method that returns an EJSON array (which is returned by a Cursor.fetch()
call), which works like so:
Meteor.call("search", {}, console.log)
but does not work like so:
MeteorObservable.call("card_search", {}).subscribe(console.log)
In the first example, an Array is logged to the console, in the second, the console shows undefined
.
I'm experiencing currently an issue when trying to map over an empty result set.
For example, when I try to do:
Collection.find(condition).map(x => ....)
the map callback will not be called if the result of find is empty.
Is that behaviour according to the design?
Hello and thanks for nice lib!
Is any way to use 'collection-helpers' module
( https://atmospherejs.com/dburles/collection-helpers )
with meteor-rxjs?
Thanks!
I tried to use the Counts (https://github.com/percolatestudio/publish-counts) package in following way
Meteor.publish('commentCountPub', function(userId: string) {
Counts.publish(this, 'commentCount', Comments.find(buildQuery.call(this, userId)).Cursor());
});
I got the error: TypeError: notifications_collection_1.Notifications.find(...).Cursor is not a function
How i can get cursor from the MongoObservable collection?
I am not 100% sure where to go with this one (but pretty sure its meteor-rxjs), or even if I am doing something wrong.
I have an outer subscription that is waiting on the user to login, then triggers an inner subscription that fetches data for the logged in user.
The issue is that the find for the inner subscription does not return the data. I know the objects are in the local mongo. I know the find function is called. It just doesnt return the data. However, if I pull the find out of the login subscription. It returns the data just fine. Here is some code
Angular4 + typescript
//user class
private userState: BehaviorSubject<string> = new BehaviorSubject(null);
whenLoggedIn() : Observable<string> {
return this.userState;
}
//ui controller
ngOnInit() {
let thiss = this;
this.test = this.users.whenLoggedIn()
.subscribe(user=>{
if(user == "loggedIn"){
thiss.findData();
} else {
thiss.ngOnDestroy();
}
this.loggedIn = user;
});
}
ngOnDestroy() {
if(this.subThMod) {
this.subThMod.unsubscribe();
}
}
findData() {
this.subThMod = this.thWaMe_OuSe.findAll()
.subscribe(val=>{
debugger;
});
}
public findAll(): Observable<ModelThWaMe_OuSe[]> {
//Model = substantiated mongo collection observable
var ret = this.Model.find({})
.auditTime(50)
.do(()=>{
CommonLogic.debug(this, "ThWaMe_OuSe:findAll_idList");
})
.map(raws => {
return raws.map(raw=> {
return this.newModel(raw);
});
});
return ret;
}
the flow is this start->outerSub["loggedOut"]->ngOnDestroy()->outerSub['loggedIn']->findData()
then the debugger never hits.
However, 'findData()' constructor the debugger hits when the user is logged in (with user data).
I think its an meteor-rxjs issue due to this function works as expected when replaced with pure RXJS
function findData(){
Rx.Observable.interval(1000).mapTo("inner")
.subscribe((valI)=>{
console.log(valI);
});
}
Here will constantly output "inner" to the console as expected.
here is a jsbin for my situation and also what I would expect using pure RSJS.
http://jsbin.com/giliqip/edit?js,console
Thanks for your help.
I was wondering if there was a particular reason that MeteorObservable.call()
is implemented using Observer.create()
?
I would like to make multiple subscriptions to the observable returned by MeteorObservable.call()
. However, doing this causes the function passed to Observable.create(subscribe: Function)
inside MeteorObservable.call()
to be called each time the Observable.subscribe()
method is called. This means that the Meteor.call()
method gets called several times instead of just once. Is this the intended behaviour & if so:
BehaviorSubject
so that it is only ever called once & can still cater for 1 subscription? It would not be backward compatible for those who are currently relying on the fact that the Meteor.call()
is only made when Observable.subscribe()
is called.I realise that I could just wrap the MeteorObservable.call()
in my own observer to accomplish this but I was just surprised to find that the method was being called each time I subscribed to the observable; and thought it was worth making an issue here.
What I am doing:
Client
let observable: Observable = MeteorObservable.call('some.meteor.method');
...
observable.subscribe(()=>{
console.log('subscription 1');
});
...
observable.subscribe(()=>{
console.log('subscription 2');
});
SERVER
Meteor.methods({
'some.meteor.method': function() {
console.log('method called');
}
});
What I am expecting in the server console:
method called
What I am actually getting in the server console:
method called
method called
The above is pseudo code to illustrate my point
Hi @barbatus
Can you please suggest how it is possible to use this package within services. I tried to use it but got no results.
export class NotificationDataService extends MeteorComponent implements OnInit {
user: Meteor.User;
notifications: Observable < Notification[] > ;
data: Notification[];
notificationSub: Subscription;
constructor(private ngZone: NgZone) {
super();
}
ngOnInit() {
}
subscribeNotifications(userId: string): Observable < Notification[] > {
let notificationsOptions = {
sort: { updatedAt: -1 }
};
this.notificationSub = MeteorObservable
.subscribe('notifications', notificationsOptions, userId)
.subscribe(() => {
this.notifications = Notifications.find({ notificationToId: userId },
notificationsOptions)
.debounce(() => Observable.interval(50))
.zone();
return this.notifications;
});
return this.notifications;
}
getSubscription(){
return this.notifications;
}
}
When i tried to call subscribeNotifications(userId) i get this.notifications undefined in my Component. I even tried to wrap the service call in MeteorObservable.autorun() and ngZone.run(); no results.
this.autorunSub = MeteorObservable.autorun().subscribe(() => {
this.ngZone.run(() => {
this.notifications = this.notificationDataService.subscribeNotifications(userId);
if(this.notifications){
this.notifications.subscribe(data => {
this.data = data.sort(function(a, b) {
if (a.updatedAt > b.updatedAt) {
return -1;
} else if (a.updatedAt < b.updatedAt) {
return 1;
}
return 0;
});
}, (error) => {
});
} else
console.log("notification not ready");
});
});
I get the error Maximum call stack size exceeded
when I call MeteorObservable.call('updateSpot', spot)
.
spot
is an object of
interface Spot {
_id?: string;
ownerId?: string;
tourId?: string;
title?: string;
pictures?: string[];
description?: string;
actions?: any; //TODO: change
lat?: number;
lng?: number;
}
main.js:68268 RangeError: Maximum call stack size exceeded
at Function._.each._.forEach (main.js:101883)
at Object.EJSON.clone (main.js:101887)
at main.js:101887
at Function._.each._.forEach (main.js:101883)
at Object.EJSON.clone (main.js:101887)
at main.js:101887
at Function._.each._.forEach (main.js:101883)
at Object.EJSON.clone (main.js:101887)
at main.js:101887
at Function._.each._.forEach (main.js:101883)
When I call MeteorObservable.call('updateSpot', {_id: 123, test: 456})
I get no error..
I'm in an Ionic2 project.
I'm getting the error
__extends is not defined
when trying to import the MeteorObservable or MongoObservable classes on Meteor v1.4.2.1
I've searched the repo and can see the references to __extends in the class definitions, but can't see where the method is defined?
Branch | Build failing π¨ |
---|---|
Dependency | @types/chai |
Current Version | 3.4.34 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As @types/chai is βonlyβ a devDependency of this project it might not break production or downstream projects, but βonlyβ your build or test tools β preventing new deploys or publishes.
I recommend you give this issue a high priority. Iβm sure you can resolve this πͺ
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
More info at:
Urigo/meteor-angular2.0-socially#164
I was testing insert and tried to perform subscribe to do some async action. But when using SimpleSchema
it won't work but without it works.
Is this a limitation or bug?
const boxes = new Mongo.Collection('boxes');
boxes.schema = new SimpleSchema({
_id: {
type: String,
},
name: {
type: String,
},
description: {
type: String,
optional: true,
},
lang: {
type: String,
}
}
boxes.attachSchema(boxes.schema);
const Boxes = new MongoObservable.Collection(boxes);
Boxes
.collection #-- without collection it is not inserting.
.insert({
name,
description,
lang,
}, { validate: true });
I would like to do something
Boxes.insert(doc).subscribe( str => console.log(str));
How to use this package when Pub is returning only one object (one row/record) and I try to get it using say Posts.findOne(postId);
Branch | Build failing π¨ |
---|---|
Dependency | zone.js |
Current Version | 0.7.3 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As zone.js is βonlyβ a devDependency of this project it might not break production or downstream projects, but βonlyβ your build or test tools β preventing new deploys or publishes.
I recommend you give this issue a high priority. Iβm sure you can resolve this πͺ
The new version differs by 4 commits .
1de7ea0
chore: release v0.7.4
a22a687
Revert "fix: Correct ZoneAwareError prototype chain" (#556)
c70e9ec
fix: formatting issue.
2643783
fix(closure): Fix closure error suppression comment. (#552)
See the full diff.
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
In the README you tell how to use the component i Angular2
const Tasks = new MongoObservable.Collection<Task>('tasks');
@Component({
selector: 'task-list',
template: `<ul><li *ngFor="let task of tasks | async"></li></ul>`
})
class Tasks {
tasks = Tasks.find().zone();
}
It seems to me that data will be repeated an extra time for every revisit to this component. That is
bsliran/angular2-meteor-base uses this code-pattern in the DemoComponent. In repeated-data (note branch "repeated-data") I have forked and added an extra component DemoComponent2, and set it up so that you can navigate back and forth between showing DemoComponent and DemoComponent2 (see this commit). After starting the application and pointing your browser to http://localhost:3000, if you click the "Demo"-link you will see data
If then click the "Demo 2"-link, and then the "Demo"-link you will see data
Taking another round and you will see data
I believe it has something to do with meteor-rxjs, but I am not sure. At least the problem does not occur if you are using a hardcoded data-array and no async (see this commit)
Hopefully you can help find out what is going wrong. If it is not a bug, then at least it would be nice if the README of meteor-rxjs under "Usage in Angular 2" mentioned something about this issue, and how to get around it.
Won't work:
const Tasks = new MongoObservable.Collection<Task>('tasks');
@Component({
selector: 'task-list',
template: `<ul><li *ngFor="let task of tasks | async"></li></ul>`
})
class Tasks {
tasks = Tasks.find();
}
It will but with zone()
const Tasks = new MongoObservable.Collection<Task>('tasks');
@Component({
selector: 'task-list',
template: `<ul><li *ngFor="let task of tasks | async"></li></ul>`
})
class Tasks {
tasks = Tasks.find().zone(); // <--
}
Hi,
I want to modify the collection further querying different collection(nested). How to achieve it?
Boxes : { _id: 'sdfs', server: 'server_id' ...}
Servers: { _id: 'server_id', ....}
I do publishComposite at server end and i need to receive same data at client.
const modified = (observable) => {
observable.server = Server.findOne({_id: observable.server});
return observable;
}
.mergeMap(() =>
Boxes
.find()
.forEach( observable => modified(observable)
But not receiving the data I need.
I am using the meteor-rxjs API in an Angular Service like in the snippet below. The function returns an Observable holding all results for a certain query. Since the query may be different every time this function is called, we need to do the subscription every time to make sure the correct documents are synced with the client.
getSensors(someQuery: Object): Observable<Sensor[]> {
return Observable.create(observer => {
MeteorObservable.subscribe('sensors', someQuery).subscribe(() => {
MeteorObservable.autorun().zone().subscribe(() => {
observer.next(SensorCollection.find().fetch());
});
});
});
}
While the query can be different, it can also be identical to a previous query. If the previous subscription is still live, Meteor will detect that the subscription already exists and will not execute the onReady()
callback. As a result, the observable returned by MeteorObservable.subscribe()
will never emit an event and the component requesting the data will not get it.
When an identical subscription is already live, Meteor will still return a subscription handler. This handler contains the subscriptionId
which is the same as the id of the existing subscription. However MeteorObservable
does not use this information yet. If it did MeteorObservable
could recognize a duplicate subscriptionId and issue the observer.next()
event anyway.
I implemented a solution here. This works by storing an array of live subscriptions globally and checking whether the new meteor-subscription already exists. If so, a next()
-event is emitted on the observer.
let liveSubscriptions = [];
export class MeteorObservable {
public static subscribe<T>(name: string, ...args: any[]): Observable<T> {
....
// some lines removed to save spave
....
let subHandler = null;
return Observable.create((observer: Subscriber<Meteor.Error | T>) => {
observers.push(observer);
// Execute subscribe lazily.
if (subHandler === null) {
subHandler = subscribe();
if (liveSubscriptions.find(sub => sub === subHandler.subscriptionId)) {
// subscription already exists, call observer.next() since Meteor won't.
observer.next();
} else {
liveSubscriptions.push(subHandler.subscriptionId);
}
}
return () => {
removeObserver(observers,
observer, () => {
// remove subscription from liveSubscriptions list
let i = liveSubscriptions.findIndex(
sub => sub === subHandler.subscriptionId
);
if (i > -1) {
liveSubscriptions.splice(i, 1);
}
subHandler.stop();
});
};
});
}
}
I tested this, and it seems to work fine.
The only things is, Is there a better solution for the global array that now lives in this file. Maybe it would be nice to have a local context of live subscriptions. For example per Angular Service.
I get this error when building in Angular 5.0 with Angular CLI 1.5 using --prod flag.
The issue is misaligned Observable and Subject import in MeteorObservable.js, ObservableCursor.js, and zone.js and ObservableCollection.js
Change imports to;
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Subscriber } from 'rxjs/Subscriber';
Seen here; angular/angular-cli#7110
Following the example in "Usage in Angular 2" section, when the app is running inside an iframe. The response of the subscribed collection records arrives to the client, but the observable map (or zone) function is not being called. is there any limitation on working inside an iframe?
The code inside the callback of a MongoObservable subscription is not updating the view. Its working when I put zone.run(). Before the update I used v0.6 without problems.
I have the following error trying to create a observable collection:
W20161005-08:40:54.003(-5)? (STDERR) Error: Must pass options before Method is defined: /users/insert
W20161005-08:40:54.003(-5)? (STDERR) at Object.SimpleRest.setMethodOptions (packages/simple_rest/rest.js:25:1)
W20161005-08:40:54.004(-5)? (STDERR) at Object.Meteor.method (packages/simple_rest/rest.js:99:1)
W20161005-08:40:54.004(-5)? (STDERR) at packages/simple_rest/rest.js:180:1
W20161005-08:40:54.004(-5)? (STDERR) at Function._.each._.forEach (packages/underscore/underscore.js:113:1)
W20161005-08:40:54.007(-5)? (STDERR) at Server.Meteor.methods.Object.getPrototypeOf.methods [as methods] (packages/simple_rest/rest.js:179:1)
W20161005-08:40:54.007(-5)? (STDERR) at packages/allow-deny/allow-deny.js:202:22
W20161005-08:40:54.007(-5)? (STDERR) at [object Object].CollectionPrototype._defineMutationMethods (packages/allow-deny/allow-deny.js:108:84)
W20161005-08:40:54.008(-5)? (STDERR) at [object Object].Mongo.Collection._defineMutationMethods (packages/simple_rest/rest.js:173:1)
W20161005-08:40:54.008(-5)? (STDERR) at new Mongo.Collection (packages/mongo/collection.js:240:12)
W20161005-08:40:54.008(-5)? (STDERR) at new Collection (/node_modules/meteor-rxjs/dist/ObservableCollection.js:14:36)
I thinks it's related to simple-rest meteor package:
https://github.com/stubailo/meteor-rest/blob/devel/packages/rest/rest.js#L25
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.