Exploring the integration of the mongodb-stitch library within an Angular 4 application

I have been experimenting with the MongoDB Stitch service in Angular, and so far I have successfully implemented the service. However, the only way I have managed to connect to the service is by adding the js library hosted on AWS directly into the html page.

While there is a mongodb-stitch npm package available and tutorials on how to use it, unfortunately, this is a pure JS library without TypeScript support. Despite trying various methods such as using require, installing typings (which are not available), and attempting to add @types, I have not had success.

Has anyone tried integrating the 'mongodb-stitch' package in Ng4? I would greatly appreciate any guidance or steps taken to utilize this package and create a service.

Answer №1

The previous response mentioned the instantiation of a new instance of StitchClient, which MongoDB has explicitly advised against in the Official API Documentation. It is recommended to use the factory method provided for this purpose. After installing mongodb-stitch, you can begin by adding the following code in your component.ts file:

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

You can then utilize this setup for various purposes, such as implementing Google sign-in functionality:

gLogin(){
this.mClient.then(stitchClient => {
  stitchClient.authenticate("google");
})

Answer №2

It's uncertain if the question is still applicable since it was posed two months ago, but let's address it nonetheless...

As you mentioned, you have the option to utilize

npm install --save mongodb-stitch
for installing the package. Given that there is no TypeScript binding available, you can define the stitch library as any

Here's an 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"));
    }

Answer №3

While the previous solutions work fine, I'd like to demonstrate an example using an injectable service.

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 creating the previous file, you need to create a module to handle the data:

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

Don't forget to add the service in the initial declarations of module.ts.

Explore mongodb Atlas

Check out mongodb-stitch via NPM

Read the documentation for mongoDB Stitch.

Definitely!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular CLI does not recognize any Bootstrap classes

While working on my Angular project and utilizing Bootstrap along with various libraries, I suddenly encountered an issue where all CSS classes associated with Bootstrap are not being detected. In the angular.json file: "styles": [ &qu ...

Locate every instance where two arrays are compared in TypeScript

My goal is to search for matches in Object 2 where the _type corresponds to filterByCallTypeTitulo in Object 1, and then create a new array including all the matched information from Object 2. I attempted to achieve this using the filter() method and forE ...

Disabling past dates on Kendo datepicker in Angular 2: A step-by-step guide

<kendo-datepicker formControlName="departureValue" [format]="'MMM-dd-yyyy'" (click)="ChangeReturnDate()"></kendo-datepicker> Is there a way to accomplish this in my code? ...

Setting a value in the selectpicker of rsuitejs involves assigning a specific value to the

const _DATA = [{ code: 'code1', name: 'Jagger' },{ code: 'code2', name: 'Tigger' },{ code: 'code3', name: 'Lion' }] <SelectPicker data={_DATA.map(x => {return {label: x.n ...

The function type '() => JSX.Element' cannot be assigned to the type 'ReactNode'

I am encountering an issue while trying to display a component using an object. The code is throwing an error: const Login = () => <>login</> const publicRoutes = [ { path: '/login', component: Login } ] function AppR ...

TS2304: The build process is unable to locate the name 'iterable' within @types

As an experienced dog attempting to master new tricks like npm and TypeScript, I find myself faced with a challenge in my Visual Studio 2017 project. Despite setting it to "Latest" TypeScript 2.5 and adding @types/jquery (3.2.12), the project keeps throwin ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

Delaying the tap after emitting an action in the Ngrx store

Within the realm of Ngrx store, I am currently utilizing 2 effects: @Effect({ dispatch: false }) toastSuccess$ = this.actions$ .pipe( ofType(TOAST_SUCCESS), map((action: any) => this.toastr.success(action.payload, &a ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

Tips for implementing the select all feature in mat-checkbox for Angular 5

Here is the code snippet from my HTML template: <mat-card> <mat-card-content> <h2 class="example-h2">Select Employee</h2> <section class="example-section"> <mat-checkbox [(ngModel)]="ch ...

Pile of automatically generated elements

Within our application, a dynamic panel has been implemented to load various forms. The panel service is responsible for receiving information about which form to load, and the panel component then handles the creation and loading of the specific form usin ...

Troubleshooting Ng Serve Module Conflict

My latest project involved creating a chatbot system. However, whenever I try to open the system, an error pops up on the command prompt. I attempted to troubleshoot by uninstalling and reinstalling npm, but the issue persists. Below is a link to an image ...

What is the best way to incorporate ControlContainer in an Angular component's unit test?

Is there a way to include ControlContainer in an Angular unit test? The error message I am encountering reads: NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]: StaticInjectorError(Platform: core) ...

Updating an Object using Angular's @Input() feature

I am facing an issue with my GameStats Object, which is part of a self-defined interface. When I update the value of an attribute, the child component does not recognize the change. I have tried using ngOnChanges, but it does not get triggered, and ngDoChe ...

Unresponsive display on both 'Ionic development application' and 'physical mobile device'

As a newbie to Ionic, I recently delved into the world of Ionic 4 by following the guidance provided in the Ionic 4 documentation. After setting up my project using ionic start myApp sidemenu --type=angular, I noticed that everything ran smoothly on my bro ...

Saving an array of strings with Mongoose

I am encountering an issue while trying to save an array of strings into my database using Mongoose. (Please note that the code provided below has been simplified for clarity) To provide some context, I have a person schema and I try to save the tags lik ...

What is the proper method for transferring a JWT token to an external URL?

I currently have two REST endpoints set up: accounts.mydomain.com/login - This is an identity provider that sends a JWT token as a response once a user is authenticated with their username and password. api.mydomain.com/users - This endpoint accepts the ...

A comprehensive guide on using HttpClient in Angular

After following the tutorial on the angular site (https://angular.io/guide/http), I'm facing difficulties in achieving my desired outcome due to an error that seems unclear to me. I've stored my text file in the assets folder and created a config ...

Sending data between components in Angular can be achieved by using various methods. One common approach is to utilize

I am encountering an issue with a component named customers.component Below is the code from the customers.component.ts file: @Component({ selector: 'app-customer', templateUrl: './customer.component.html', styleUrls: ['./cu ...

Prevent entry into property in Ionic 2 course

I receive a dynamic translation file from a server periodically, and I'm unable to modify its format. When a new page is instantiated in my Ionic App, I assign the value from storage to this.translations. See the constructor below: constructor(stora ...