【问题标题】:MongoDB Stitch and Angular 6 applicationMongoDB Stitch 和 Angular 6 应用程序
【发布时间】:2018-08-03 21:37:51
【问题描述】:

我正在为我的 MongoDB Stitch 连接创建一个服务,但我遇到了一个问题,如果我刷新我的页面,我会收到一条错误消息:

应用程序“xyxyxyxyxyxy”的客户端尚未初始化

当我尝试初始化它时,我收到一条错误消息,说它已经被初始化了。

应用程序“xyxyxyxyxyxy”的客户端已经初始化

这是我的服务。

import { Injectable } from '@angular/core';
import { Stitch, RemoteMongoClient, UserApiKeyCredential} from 'mongodb-stitch-browser-sdk';

@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {
  client: any;
  credential: UserApiKeyCredential;
  db: any;

  constructor() {
    console.log(Stitch.hasAppClient('xyxyxyxyxyxy'));
    if (!Stitch.hasAppClient('xyxyxyxyxyxy')) {
      this.client = Stitch.initializeDefaultAppClient('xyxyxyxyxyxy');
    } else {
      console.log('here');
      this.client = Stitch.initializeAppClient('xyxyxyxyxyxy');
      //this.client = Stitch.getAppClient('xyxyxyxyxyxy');
    }

    this.db = this.client.getServiceClient(RemoteMongoClient.factory, 'mongodb-atlas').db('DBNAME');
  }

  login() {
    this.credential = new UserApiKeyCredential('APIKEY');
    this.client.auth.loginWithCredential(this.credential)
      .then(authId => {
        console.log(authId);
      });
  }

  logout() {
    this.client.auth.logout()
      .then(resp => {
        console.log(resp);
      });
  }

  insertData(collectionName: string, data: {}) {
    this.db.collection(collectionName).insertOne(data)
      .then(resp => {
        console.log(resp);
      });
  }

  getData(collectionName: string) {
    this.db.collection(collectionName).find({})
      .asArray().then(resp => {
        console.log(resp);
      });
  }
}

【问题讨论】:

    标签: mongodb angular6 mongodb-stitch


    【解决方案1】:

    将构造函数更改为这样,它可以解决问题。

    constructor() {
        if (!Stitch.hasAppClient('xyxyxyxyxyxy')) {
            this.client = Stitch.initializeDefaultAppClient('xyxyxyxyxyxy');
        } else {
            this.client = Stitch.defaultAppClient;
        }
    
        this.db = this.client.getServiceClient(RemoteMongoClient.factory, 'mongodb-atlas').db('DBNAME');
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 2019-05-30
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多