Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.
There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using #types) to no avail.
Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.
The other answer suggests instantiating a new instance of StitchClient which is something that MongoDB have explicitly advised against in the Official API Documentation - and with reason, since there is a factory method available for that purpose. So, (after installing mongodb-stitch), the following code would help you get started in component.ts
import { Component, OnInit } from "#angular/core";
import { StitchClientFactory } from "mongodb-stitch";
let appId = 'authapp-****';
#Component({
selector: "app-mongo-auth",
templateUrl: "./mongo-auth.component.html",
styleUrls: ["./mongo-auth.component.css"]
})
export class MongoAuthComponent implements OnInit {
mClient;
ngOnInit() {
this.mClient = StitchClientFactory.create(appId);
}
And you can then use this for whatever purpose you want, such as for implementing sign-in with Google
gLogin(){
this.mClient.then(stitchClient => {
stitchClient.authenticate("google");
})
not sure whether the question is still relevant considering it was asked two months ago but anyway...
As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any
For example:
declare var stitch: any;
export class MyService implements OnInit {
db;
client;
ngOnInit() {
this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
this.client.login();
}
save() {
this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
}
}
the previous answers are functional, but i wanna share a example using a service injectable.
service.ts
import { Injectable } from '#angular/core';
import { Jsonp, URLSearchParams } from '#angular/http';
import { StitchClientFactory } from "mongodb-stitch";
import 'rxjs/add/operator/map';
#Injectable()
export class Service {
constructor(private jsonp: Jsonp) { }
client;
connect(){
this.client = new StitchClientFactory.create("App ID"); // Slitch apps > Clients > App ID
this.client.then(stitchClient => stitchClient.login())
.then((stitchClient) => console.log('logged in as: ' + stitchClient))
.catch(e => console.log('error: ', e));
}
all() {
this.connect();
return this.client.then(stitchClient => {
let db = stitchClient.service('mongodb', 'mongodb-atlas').db("database Name"); // Slitch apps > mongodb-atlas > Name database.Collection
let itemsCollection = db.collection('name collection'); // Slitch apps > mongodb-atlas > Name database.Collection
console.log(itemsCollection.find().execute());
return itemsCollection.find().execute();
})
.then(result => {return result})
.catch(e => console.log('error: ', e));
}
}
after make the previous file, you must create a module to receive the data, so:
module.ts
import { Component, OnInit, Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import { StitchClientFactory } from "mongodb-stitch";
import { Service } from 'service'; // previous code
declare var stitch: any;
#Component({
template: '
<ul class="demo-list-icon mdl-list">
<li class="mdl-list__item" *ngFor="let item of data | async">
<span class="mdl-list__item-primary-content">
<i class="material-icons mdl-list__item-icon">{{propiedad.nombre}}</i>
</span>
</li>
</ul>
'
})
export class MainComponent implements OnInit {
data: Observable<[]>;
constructor(private Service: service) {
}
ngOnInit() {
this.propiedades = this.Service.all();
}
}
important, you don´t must forget to add service on module.ts intitial declarations.
mongodb Atlas
mongodb-stitch vía NPM
Documentation mongoDB Stitch.
Sure!
Related
I have deployed React App in LWC component without using Aura container basically bundle react application with webpack as static resource and use them inside a LWC and able to render.
able to open individual stylesheet for debugging purpose.
Question: Not able to debug the code/not opening individual JS file/component in developer console.
lwcReactContainer.html
<template>
<div id="react-app-root"></div>
</template>
lwcReactContainer.js
import { LightningElement, wire } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import SPMLayoutEditor1 from '#salesforce/resourceUrl/SPMLayoutEditor1';
//import myStaticStyles from '#salesforce/resourceUrl/myStaticStyles';
import {
APPLICATION_SCOPE,
createMessageContext,
MessageContext,
publish,
releaseMessageContext,
subscribe,
unsubscribe,
} from 'lightning/messageService';
import getContactList from '#salesforce/apex/ContactController.getContactList';
export default class LWCReactContainer extends LightningElement {
renderedCallback() {
this.apiInProgress = true;
Promise.all([
loadScript(this, SPMLayoutEditor1 + '/FSLMAX_LayoutEditor/static/js/main.js'),
loadStyle(this, SPMLayoutEditor1 + '/FSLMAX_LayoutEditor/static/css/main.css'),
this.getUserInfo(), this.getContactList(), this.fetchObjectList()
]).then((data) => {
const contacts = data[3];
mount(this.template.querySelector('div'), { contacts });
});
}
I have been fiddling with moving a tutorial I did in Vue to Nuxt. I have been able to get everything working, however I feel I'm not doing it the "proper way". I have added the Nuxt axios module, but wasnt able to get it working, so I ended up just using the usual axios npm module. Here is my store:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
export const state = () => ({
events: []
})
export const mutations = {
setEvents: (state, events) => {
state.events = events
}
}
export const actions = {
loadEvents: async context => {
let uri = 'http://localhost:4000/events';
const response = await axios.get(uri)
context.commit('setEvents', response.data)
}
}
I would like to know how to re-write this store using the #nuxtjs/axios module. I also didnt think I'd need to import vuex here, but if I dont, my app doesn't work.
Thanks for any help!
Using the #nuxtjs/axios module, you can configure axios inside your nuxt.config.js:
// nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
],
axios: {
// proxy: true
}
}
You can use it inside your store (or components) with this.$axios
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}
I am trying to get my angular webapp working with a star sp 700 receipt printer and am trying to integrate qz-tray into my software for that reason. I am getting an error when trying to install #types/qz-tray which is displayed below. Also I get an error
unresolved variable websocket
on the line 23 and
unresolved variable api
on line 16.
Can someone please tell me how to fix this and if there is a better way of printing to either this or another receipt printer through angular?
import { Injectable } from '#angular/core';
import { from as fromPromise, Observable, throwError } from 'rxjs';
import { HttpErrorResponse } from '#angular/common/http';
import { catchError, map } from 'rxjs/operators';
import * as qz from 'qz-tray';
import { sha256 } from 'js-sha256';
#Injectable({
providedIn: 'root'
})
export class PrinterService {
//npm install qz-tray js-sha256 rsvp --save
constructor() {
qz.api.setSha256Type(data => sha256(data));
qz.api.setPromiseType(resolver => new Promise(resolver));
}
// Get the list of printers connected
getPrinters(): Observable<string[]> {
console.log('+++++++++PrinterService+++++');
return fromPromise(
qz.websocket.connect().then(() => qz.printers.find())
)
map((printers: string[]) => printers)
, catchError(this.errorHandler);
}
// Get the SPECIFIC connected printer
getPrinter(printerName: string): Observable<string> {
return fromPromise(
qz.websocket.connect()
.then(() => qz.printers.find(printerName))
)
map((printer: string) => printer)
, catchError(this.errorHandler);
}
// Print data to chosen printer
printData(printer: string, data: any): Observable<any> {
const config = qz.configs.create(printer);
return fromPromise(qz.print(config, data))
map((anything: any) => anything)
, catchError(this.errorHandler);
}
private errorHandler(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error);
console.log('An error occurred:', error.status);
return throwError(error.error);
} else {
console.log('An error occurred:', error.status);
console.log(error.error);
return throwError(error.error);
}
};
}
unresolved variable websocket
unresolved variable api
These are both signs that qz-tray.js did not load properly.
The objects qz.api and qz.websocket are both part of the qz namespace. If they're not available, then qz was never imported properly.
Here's a working example of QZ Tray running in Angular:
https://stackblitz.com/edit/angular-3h4cnv
The import line appears to be correct and matches that of the QZ Tray angular quickstart guide.
The import * as qz should be valid according to TypeScript guidelines on exporting the default export of a module however you can safely convert it to import { default as qz } from "qz-tray";
As a troubleshooting step, you can call:
console.log(qz);
If loaded properly, it should show something like this:
Another troubleshooting technique would be to remove and reinstall qz-tray using your preferred package manager npm uninstall qz-tray; npm install qz-tray, etc.
I tried to use tensorflowjs in ionic. After converting existing model from python then import from ionic it works only when i runs on my local server (http://localhost:8100/ionic-lab)
However, when i build the project for android
tf.loadModel method not working, it fails to load model from local folder ( ie. assets/model )
I already checked this link Tensorflow.js with react-native
, but it doesn't help. I guess, lots of hybrid mobile app frameworks are pretty much the same line. Any advice and suggestions will be greatly appreciated.
import {Component} from '#angular/core';
import {IonicPage, AlertController} from 'ionic-angular';
import {HttpClient} from "#angular/common/http";
import * as tf from "#tensorflow/tfjs";
#IonicPage()
#Component({
selector: 'page-tfpretrainedversion',
templateUrl: 'tfpretrainedversion.html',
})
export class TfpretrainedversionPage {
kerasTraindedModel: tf.Model;
KERAS_MODEL_JSON = 'assets/model/model.json';
constructor(private httpClient: HttpClient,
private alertCtrl: AlertController) {
this.loadPretrainedModel();
}
loadPretrainedModel() {
tf.loadModel(this.KERAS_MODEL_JSON)
.then((result) => {
this.kerasTraindedModel = result;
})
.catch((error)=>{
let prompt = this.alertCtrl.create({
title: 'Error',
subTitle: error,
buttons: ['OK']
});
prompt.present();
});
}
}
Here is an error message
Failed to fetch
And here is a project structure
Project structure
TensorflowJs loads the models via fetch(). fetch() does not support loading local-files. https://fetch.spec.whatwg.org/
My Workaround:
Use a polyfill (https://github.com/github/fetch) and replace the fetch.
window.fetch = fetchPolyfill;
Now, it's possible to load local files (file:///) like:
const modelUrl = './model.json'
const model = await tf.loadGraphModel(modelUrl);
I am trying to integrate ams-amplify with NativeScript but I am not able to get it to work successfully.
import { Component, OnInit } from "#angular/core";
require("nativescript-nodeify");
var Amplify = require("aws-amplify");
#Component({
selector: "Home",
moduleId: module.id,
templateUrl: "./home.component.html"
})
export class HomeComponent implements OnInit {
constructor() {
// Use the component constructor to inject providers.
Amplify.configure({
Auth: {
// REQUIRED - Amazon Cognito Identity Pool ID
identityPoolId: 'xxxxx',
// REQUIRED - Amazon Cognito Region
region: 'xxxx',
// OPTIONAL - Amazon Cognito User Pool ID
userPoolId: 'xxxx',
// OPTIONAL - Amazon Cognito Web Client ID
userPoolWebClientId: 'xxxxx',
}
});
}
ngOnInit(): void {
}
}
But I am getting some "navigator is not defined" error.
JS: ERROR Error: Uncaught (in promise): ReferenceError: navigator is
not defined JS: ReferenceError: navigator is not defined JS: at
standardBrowserEnv
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/helpers/isURLSameOrigin.js:11:39)
JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/helpers/isURLSameOrigin.js:60:5)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/adapters/xhr.js:7:23)
JS: at require (:1:266) JS: at getDefaultAdapter
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/defaults.js:20:15)
JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/defaults.js:29:12)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/core/Axios.js:3:16)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/lib/axios.js:5:13)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/axios/index.js:1:78)
JS: at require (:1:266) JS: at Object.
(file:///data/data/org.nativescript.awsamplify/files/app/tns_modules/aws-amplify/lib/API/RestClient.js:70:15)
If anyone has working code, please share.
The problem is with latest version of aws-amplify.
Changed it to "aws-amplify": "^0.2.9" version and everything working fine now :)
Edit: Working Solution with latest Amplify version
import * as storage from "nativescript-localstorage";
import { Buffer } from "buffer";
import "nativescript-nodeify";
global["window"] = {};
global["window"]["localStorage"] = storage;
global["window"]["addEventListener"] = args => {
return args;
};
global["window"]["navigator"] = {};
global["window"]["Buffer"] = Buffer;
global["window"]["setTimeout"] = setTimeout;
global["window"]["clearTimeout"] = clearTimeout;
global["navigator"] = {};
global["navigator"]["product"] = "ReactNative";
import Amplify, { Auth, Storage } from "aws-amplify";
import aws_config from "~/aws-exports";
Amplify.configure(aws_config);