Как интегрировать модуль @ azure / cosmos в угловое веб-приложение - PullRequest
0 голосов
/ 05 мая 2019

В настоящее время я разрабатываю веб-приложение на основе Angular и хочу подключить его к базе данных Azure Cosmos DB.

Что я сделал до сих пор:

  1. Выполнить npm установить @ azure / cosmos --save

-> теперь модуль get указан в node_modules и package.json

  1. Я пошел в папку node_modules / @ azure / cosmos и добавил файл app.js с этим демонстрационным контентом:
const cosmos = require("@azure/cosmos");
const CosmosClient = cosmos.CosmosClient;

const endpoint = "[hostendpoint]"; // Add your endpoint
const masterKey = "[database account masterkey]"; // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, auth: { masterKey } });

const databaseDefinition = { id: "sample database" };
const collectionDefinition = { id: "sample collection" };
const documentDefinition = { id: "hello world doc", content: "Hello World!" };

async function helloCosmos() {
  const { database: db } = await client.databases.create(databaseDefinition);
  console.log("created db");

  const { container } = await db.containers.create(collectionDefinition);
  console.log("created collection");

  const { body } = await container.items.create(documentDefinition);
  console.log("Created item with content: ", body.content);

  await db.delete();
  console.log("Deleted database");
}

helloCosmos().catch(err => {
  console.error(err);
});
  1. У меня есть файл angular.json в моей основной директории. Я добавил следующее:

"scripts": ["node_modules/@azure/cosmos/app.js"],

-> Вот мой первый вопрос, правильно ли указывать на app.js?

-> Это пример моего header.component.ts :

// Angular
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { NavigationCancel, NavigationEnd, NavigationStart, RouteConfigLoadEnd, RouteConfigLoadStart, Router } from '@angular/router';
// Object-Path
import * as objectPath from 'object-path';
// Loading bar
import { LoadingBarService } from '@ngx-loading-bar/core';
// Layout
import { LayoutRefService, LayoutConfigService } from '../../../../core/_base/layout';
// HTML Class Service
import { HtmlClassService } from '../html-class.service';


@Component({
    selector: 'kt-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit, AfterViewInit {
    // Public properties
    menuHeaderDisplay: boolean;
    @ViewChild('ktHeader') ktHeader: ElementRef;

    /**
     * Component constructor
     *
     * @param router: Router
     * @param layoutRefService: LayoutRefService
     * @param layoutConfigService: LayoutConfigService
     * @param loader: LoadingBarService
     * @param htmlClassService: HtmlClassService
     */
    constructor(
        private router: Router,
        private layoutRefService: LayoutRefService,
        private layoutConfigService: LayoutConfigService,
        public loader: LoadingBarService,
        public htmlClassService: HtmlClassService
    ) {
        // page progress bar percentage
        this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                // set page progress bar loading to start on NavigationStart event router
                this.loader.start();
            }
            if (event instanceof RouteConfigLoadStart) {
                this.loader.increment(35);
            }
            if (event instanceof RouteConfigLoadEnd) {
                this.loader.increment(75);
            }
            if (event instanceof NavigationEnd || event instanceof NavigationCancel) {
                // set page progress bar loading to end on NavigationEnd event router
                this.loader.complete();
            }
        });
    }

    /**
     * @ Lifecycle sequences => https://angular.io/guide/lifecycle-hooks
     */

    /**
     * On init
     */
    ngOnInit(): void {
        const config = this.layoutConfigService.getConfig();

        // get menu header display option
        this.menuHeaderDisplay = objectPath.get(config, 'header.menu.self.display');

        // animate the header minimize the height on scroll down
        if (objectPath.get(config, 'header.self.fixed.desktop.enabled') || objectPath.get(config, 'header.self.fixed.desktop')) {
            // header minimize on scroll down
            this.ktHeader.nativeElement.setAttribute('data-ktheader-minimize', '1');
        }
    }

    ngAfterViewInit(): void {
        // keep header element in the service
        this.layoutRefService.addElement('header', this.ktHeader.nativeElement);
    }
}

Что мне нужно добавить в этот код? И как мне вставить значения результата из моего запроса к БД в мой необработанный HTML-файл?

...