Применение MongoDB Stitch и Angular 6
Я создаю сервис для моих подключений 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);
});
}
}
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');
}