首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >MongoDB缝角6应用

MongoDB缝角6应用
EN

Stack Overflow用户
提问于 2018-07-26 17:25:15
回答 1查看 600关注 0票数 1

我正在为我的MongoDB Stitch连接创建一个服务,而且我遇到了一个问题,如果我刷新页面,就会看到一个错误:

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

当我试图初始化它时,我会得到一个错误,它已经被初始化了。

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

这是我的服务。

代码语言:javascript
运行
复制
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);
      });
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-03 13:37:51

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

代码语言:javascript
运行
复制
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');
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51544430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档