Git Product home page Git Product logo

meteor-rxjs's Introduction

Meteor + RxJS

npm version Build Status bitHound Overall Score bitHound Code bitHound Dev Dependencies

Harness Meteor reactivity with RxJS.

RxJS is built to simplify complexity dealing with reactive data flows. At the same time, Meteor's Minimongo cursors are a good target for RxJS API due to their reactivity. Thus, combining RxJS and Meteor, we bring together best parts of two worlds.

API Documentation

API documentation is available inside this repository, here.

Mongo Cursor Observable

As soon as you install this package (npm install meteor-rxjs), you have ability to use a special Mongo collection class that works with cursor observables instead of the ordinary Mongo cursors. In other words, one can subscribe on the Mongo cursor's data updates now as follows:

import {MongoObservable} from 'meteor-rxjs';

const Tasks = new MongoObservable.Collection<Task>('tasks');

Tasks.find({checked: false})
  .map(tasks => tasks.length)
  .subscribe(todoCount => console.log(todoCount));

Since this cursor observable is of RxJS’s type, every other methods and operators available to the observables as part of the RxJS API are also now available to the users, e.g., one can debounce data updates using RxJS’s debouncing operator:

import {Observable} from 'rxjs';

import {debounce, map} from 'rxjs/operators';

Tasks.find({checked: false})
  .pipe(debounce(() => Observable.interval(50)))
  .pipe(map(tasks => tasks.length))
  .subscribe(todoCount => console.log(todoCount));

Usage with Meteor packages

Meteor has a lot of packages that extend Mongo.Collection with new methods. Since MongoObservable.Collection is a wrapper over Mongo.Collection, you can't use new methods on observable instances directly. The solution here is to pass Mongo.Collection's instance to the observable constructor, and use them whenever you need after separately:

let collection = new Mongo.Collection('foo');
let observable = new MongoObservable.Collection(collection);
collection.attachSchema(...); // with SimpleSchema package

Usage in Angular

Angular has tight integration with RxJS since Angular is desinged to support reactive UI updates. One of the realizations of this integration is AsyncPipe, which is supposed to be used with RxJS observables.

In order to subscribe on the Mongo cursor observable's updates and iterate through the returned list of docs in Angular, one can use AsyncPipe in an Angular component as follows:

import { MongoObservable, zoneOperator } from 'rxjs';

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().pipe(zoneOperator());
}

Zone operator

As you can see above we called zoneOperator operator of the cursor observable. This is a special Zone operator that is implemeted by meteor-rxjs for the Angular users' convenience. This operator runs ngZone each time when new data arrives to the Mongo cursor observable, thus we force UI updates at the right time using it.

It makes sense to improve performance of the above Tasks component by debouncing UI updates. In this case we are using Zone operator as well:

class List {
  tasks = Tasks.find()
  .pipe(zoneOperator())
  .pipe(debounce(() => Observable.interval(50)))
  .zone();
}

##License MIT

meteor-rxjs's People

Contributors

ardatan avatar barbatus avatar dab0mb avatar dotansimha avatar dxcx avatar greenkeeper[bot] avatar ijager avatar kamilkisiela avatar renovate[bot] avatar urigo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

meteor-rxjs's Issues

Mistake in the package description ?

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

ObservableCollection.upsert() returns wrong type

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.

client find, server added->ready->changed does not trigger query update

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

"Maximum call stack size exceeded" when passing objects via MeteorObservable.call()

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.

Zone.js 0.7.4 - View not updating

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.

Calling #subscribe alters the observable behavior ?

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:

  • In the first example, new items are painted by my ngFor.
  • In the second exampe, firs all the items are removed, then all are repainted again.

Is that normal subscribe() has this kind of impact ?

An in-range update of zone.js is breaking the build 🚨

Version 0.7.7 of zone.js just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Commits

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.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Multiple subscription of the same Observable does not trigger changes on init

This is the flow:

  • obs.subscribe called for the first time -> cursor initialized and callbacks for onAdded called for all objects in the Collection
  • obs.subscribe called for second time-> does not have the history of the values, only if adding item to the collection, this subscription gets updated.

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]

ObservableCursor won't work with AsyncPipe

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(); // <--
}

fire MeteorObservable.subscribe in offline

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

findOne when not ready => undefinded

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

Repeated identical subscription use case not handled

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.

"__extends is not defined" on Meteor v1.4.2.1

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?

Subscribing in subscription loses inner subscription

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.

Get _id of an newly inserted Item

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

ERROR in ./node_modules/rxjs/observable/BoundCallbackObservable.js

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

Collection.find doesn't call map when result is empty

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?

Are there any plans to add Observable complete functionality?

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
);

Support for multiple databases

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?

An in-range update of @types/meteor is breaking the build 🚨

Version 1.3.32 of @types/meteor just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of babel-runtime is breaking the build 🚨

Version 6.23.0 of babel-runtime just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Angular 2.4

Observables do not update on client using angular 2.4 and rxjs greater than 5.0.1. Has anyone else experienced this issue?

Usage with Ground DB 2

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?

Data repeat for ever revisit of the component

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

  • The first time you visit the component the data from "tasks" is shown once
  • The second time you visit the component the data from "tasks" is shown twice
  • ...
  • The n'th time you visit the component the data from "tasks" is shown n times

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

  • Dotan (25)
  • Liran (26)
  • Uri (30)

If then click the "Demo 2"-link, and then the "Demo"-link you will see data

  • Dotan (25)
  • Liran (26)
  • Uri (30)
  • Dotan (25)
  • Liran (26)
  • Uri (30)

Taking another round and you will see data

  • Dotan (25)
  • Liran (26)
  • Uri (30)
  • Dotan (25)
  • Liran (26)
  • Uri (30)
  • Dotan (25)
  • Liran (26)
  • Uri (30)

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.

Missing typings on Subscription

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

An in-range update of zone.js is breaking the build 🚨

Version 0.7.4 of zone.js just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Commits

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.

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of @types/chai is breaking the build 🚨

Version 3.4.35 of @types/chai just got published.

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 💪


Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Incompatible with simple-rest package

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

How to use this package with services and some side effects

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");                       
                });
            });

collection.insert not working when using SimpleSchema

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 with Counts package

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?

Understanding the expected behaviour of MeteorObservable.call()

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:

  1. Is there a specific reason it was done like this? Just so that I can better understand it & learn from it.
  2. Might this scenario be reason enough to implement it as a 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

MeteorObservable.call does not seem to be working

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.

Collection.find().zone() not updating zone when server is making changes in collection

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.

Proposal, tighter integration

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?

Working with Angular2 app inside an iframe

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?

How to do nested data?

Hi,

I want to modify the collection further querying different collection(nested). How to achieve it?

Collections

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.

Rxjs operators on MongoObservable.Collection

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

MongoObservable: IDE cannot import automatically

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?

MongoObservable.Collection's #find's #forEach not iterating on observable ?

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.

Unexpected TypeError: Cannot read property 'apply' of undefined

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;
	});

querying data by toggling on client

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));
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.