MongoDB Stitch 和 Angular 6 应用

MongoDB Stitch and Angular 6 application

我正在为我的 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);
      });
  }
}

将构造函数改成这样,问题就解决了。

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