ionic 3 angularfire2 code to ionic 4 angularfire2 code - ionic-framework

i have my code with ionic 3 angular 5 working as below
getUser(uid:string){
console.log('start of getUser with uid:' + uid)
return new Promise((resolve, reject) =>
{
this.db.object("/users/" + uid).snapshotChanges().map(
(snapshot) => {return snapshot.payload.val()}
).subscribe(
res => {
console.log('response:' + res)
resolve(res)
},
err => {
console.log(err)
reject(err)
}
)
})
}
however, with ionic 4 .map does not work any more. how do i convert this code?

Just like you can see here
Starting in version 5.5 we have shipped "pipeable operators", which
can be accessed in rxjs/operators (notice the pluralized "operators").
These are meant to be a better approach for pulling in just the
operators you need than the "patch" operators found in rxjs-compat
package.
NOTE: Using rxjs or rxjs/operators without making changes to your
build process can result in larger bundles.
So now you can use map() like this:
// RxJS
import { map } from 'rxjs/operators/map';
// ...
getUser(uid:string){
console.log('start of getUser with uid:' + uid)
return new Promise((resolve, reject) => {
this.db.object("/users/" + uid)
.snapshotChanges()
.pipe(
map((snapshot) => {
return snapshot.payload.val();
})
)
.subscribe(
res => {
console.log('response:' + res)
resolve(res)
},
err => {
console.log(err)
reject(err)
}
)
})
}
Not related to the question itself but just in case, if you want your getUser() method to return a promise, you can use RXJS operators as well (instead of creating and resolving a promise), like this:
// RxJS
import { map } from 'rxjs/operators/map';
import { tap } from 'rxjs/operators/tap';
// ...
public getUser(uid: string): Promise<any> {
console.log('start of getUser with uid:' + uid)
return this.db
.object("/users/" + uid)
.snapshotChanges()
.pipe(
map((snapshot) => {
return snapshot.payload.val();
}),
tap((response) => {
console.log('response:' + response);
})
)
.toPromise()
}

Related

Return data in json after subscribe

I am using Angular 5 and want to return data from function getDionaeaResults in json format after subscribing to service
getDionaeaResults(sql) : any {
this.dionaeaService.getDionaeaConnectionLogs(sql).subscribe(res => {
this.data = res;
}),
(error: any) => {
console.log(error);
});
return this.data;
}
After calling this function, this.totalAttacks prints undefined.
getTotalAttack() {
this.totalAttacks = this.getDionaeaResults("some query")
console.log(this.totalAttacks,'attacks')
}
Would suggest using the Obseravable .map() function.
getDionaeaResults(sql) : Observable<any> {
return this.dionaeaService
.getDionaeaConnectionLogs(sql)
.map(res => res);
}
getTotalAttack(sql){
this.getDionaeaResults("some query")
.subscribe(
res => { this.totalAttacks = res; },
err => { console.log(err); }
);
}
this.getDionaeaResults is returning undefined because the service you're calling is asynchronous you have to wait for the subscribe callback. as Observables are asynchronous calls
this.data=res
might execute after the return statement. You can perhaps call that dionaeaService directly inside getTotalAttack() function, like this:
getTotalAttack(sql){
this.dionaeaService.getDionaeaConnectionLogs(sql).subscribe(res => {
this.totalAttacks = res;
}),
(error: any) => {
console.log(error);
});
}

Waterline ORM assign the result of find to a variable

I want to combine the results of 2 queries and then return them as one, like this:
test: async (req, res) => {
const valOne = TableOne.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const valTwo = TableTwo.find({ id: id })
.exec((err, result) => {
if (err) {
res.serverError(err);
}
return result;
});
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}
I understand above code won't return because it's async. How can I achieve this?
There is not much info you supply: node version, sails version, etc.
There are several approaches here:
1. Using promises
2. Using callback chaining
3. Using await/async
If you use sails 1.0 and node >= 8, your best bet is to use await/async, so your code should work like that:
test: async (req, res) => {
let valOne, valTwo;
try {
valOne = await TableOne.find({ id: id });
valTwo = await TableTwo.find({ id: id });
} catch (err) {
return res.serverError(err); //or res.badRequest(err);
}
const data = {
keyOne: valOne,
keyTwo: valTwo,
};
res.json(data);
}

How to convert promise to observable angular2?

I have used promise in angular2 but my requirement was done by the observable method.
Component.ts:-
constructor(private MenuService:MenuService, private router: Router ) {
this.getMenuPermissions().then(() => this.menuList = this.router.config);
}
ngOnInit() { }
getMenuPermissions(){
let promise = new Promise((resolve, reject) => {
this.MenuService.getMenuPermission()
.subscribe( res => {this.apiResponse = res},
err => reject(),
() => this.response(this.apiResponse, resolve)
);
});
return promise;
}
response(response, resolve)
{
if(response.api_status == 1)
{
this.menuPermissions = response.data;
return resolve();
}
}
My overall requirement is: - Call the service firstly and the call the HTML function. Using promise method is done but done by the observable method. I have no idea how to do? Please convert this code in the observable method.
You can done like this,
Observable.fromPromise(funcReturnsPromise())

GraphQL x MongoDB

I'm trying to read some data from a mongodb database with graphql and mongoose but everytime I query the db it returns null but no error is thrown.
Here's the code:
// Controller.js
exports.user_read = function(id) {
return new Promise((resolve, reject) => {
Contact.findById(id, function(err, user) {
err ? reject(err) : resolve(user);
}
});
}
// Resolver.js
var contact = require('Controller');
...
// root object passed as rootValue to graphqlHTTP
getUser: ({ id }) => {
contact.user_read(id)
}
...
Any tips and help would be appreciated.
P.S. This also seems to be happening with all my queries which take the same Promise format in the controller.js file.
You need to await contact.user_read(id). Without the await, you are simply sending back a Promise. It's most likely pending when it is returned, therefore the null return.
Including Daniel Rearden's suggestion to get rid of the extra Promise, here's what your code would look like:
// Controller.js
exports.user_read = async id => {
return Contact.findById(id, (err, user) => {
err ? reject(err) : resolve(user);
});
}
// Resolver.js
var contact = require('Controller');
...
// root object passed as rootValue to graphqlHTTP
getUser: ({ id }) => {
return await contact.user_read(id)
}
...

ES6 Promises in express app not properly resolving data

I'm writing an a async function with ES6 promises, that 1) saves the query parameters for a user 2) fetches data from mongodb using mongoose, 3) manipulates the json into a DSL, 4) and queries another db with it.
mongoose": "^4.7.7"
//myController.js
const myQuery = require('../models/myQuery_model');
require('mongoose').Promise = global.Promise
const uuidV4 = require('uuid/v4');
exports.saveNewQuery = function(req, res, next) {
const rawQuery = req.body;
const queryToStore = new myQuery(rawQuery);
const uid = uuidV4();
const queryToStore.uid = uid
queryToStore.save().then(() => {
fetchQueryFromMongo(uid);
}).then((storedQuery) => {
compileQueryToString(storedQuery);
}).then((queryString) => {
fetchResultsFromOtherDb(queryString);
}).then((results) => {
res.json({ results });
}).catch((error) => {
console.log(error)
})
}
Currently I'm not able to resolve the response from mongodb step 2. Still, the controllter goes on to compileQueryToString rather than catch the error from fetchQueryFromMongo
// fetchQueryFromMongo.js
const myQuery = require('../models/myQuery');
require('mongoose').Promise = global.Promise
module.exports = (uid) => {
return new Promise(
(resolve, reject) => {
myQuery.find({ uid }).then((err, res) => {
if (err) {
reject(err);
}
console.log('response success!')
resolve(res);
});
}
);
};
I'm new to promises so any tips / suggestions would be appreciated!
Make sure to return a value from your then handlers. The code below does this by using the concise body form of arrow functions.
queryToStore.save()
.then(() => fetchQueryFromMongo(uid))
.then(storedQuery => compileQueryToString(storedQuery))
.then(queryString => fetchResultsFromOtherDb(queryString))
.then(results => res.json({ results }))
.catch(console.log);