首页 > 解决方案 > Angular Openvidu 作为子组件

问题描述

Openvidu library angular 为根组件配置的库。但我想添加与子组件相同的内容。以下示例代码运行良好,打开的 vidu 组件被调用并呈现在根 URL 上。 我没有任何角度发展的想法。

打开-vidu.component.html

<div *ngIf="!session" id="join">
  <div id="join-dialog">
    <h1>Join a video session</h1>
    <form (submit)="joinSession()">
      <p>
        <label>Participant </label>
        <input type="text" id="userName" name="userName" [(ngModel)]="myUserName" required>
      </p>
      <p>
        <label>Session </label>
        <input type="text" id="sessionId" name="sessionId" [(ngModel)]="mySessionId" required>
      </p>
      <p class="text-center">
        <input type="submit" name="commit" value="Join!">
      </p>
    </form>
  </div>
</div>

<div *ngIf="session" id="session">
  <opv-session [sessionName]="mySessionId" [user]="myUserName" [token]="token" (leaveSession)="handlerLeaveSessionEvent($event)"
    (joinSession)="handlerJoinSessionEvent($event)" (error)="handlerErrorEvent($event)">
  </opv-session>
</div>
打开-vidu.component.ts

import { Component, OnInit } from '@angular/core';
import { throwError as observableThrowError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
  selector: 'app-open-vidu',
  templateUrl: './open-vidu.component.html',
  styleUrls: ['./open-vidu.component.scss']
})
export class OpenViduComponent implements OnInit {
  OPENVIDU_SERVER_URL = 'https://' + location.hostname + ':4443';
  OPENVIDU_SERVER_SECRET = 'MY_SECRET';

  // Join form
  mySessionId = 'SessionA';
  myUserName = 'Participant' + Math.floor(Math.random() * 100);
  token: string;
  session = false;

  constructor(private httpClient: HttpClient) {}

  joinSession() {
    this.getToken().then((token) => {
      this.token = token;
      this.session = true;
    });
  }

  handlerJoinSessionEvent(event): void {
    // Do something
  }

  handlerLeaveSessionEvent(event): void {
    this.session = false;
  }

  handlerErrorEvent(event): void {
    // Do something
  }

  /**
   * --------------------------
   * SERVER-SIDE RESPONSIBILITY
   * --------------------------
   * This method retrieve the mandatory user token from OpenVidu Server,
   * in this case making use Angular http API.
   * This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION. In this case:
   *   1) Initialize a session in OpenVidu Server    (POST /api/sessions)
   *   2) Generate a token in OpenVidu Server          (POST /api/tokens)
   *   3) The token must be consumed in Session.connect() method of OpenVidu Browser
   */

  getToken(): Promise<string> {
    return this.createSession(this.mySessionId).then((sessionId) => {
      return this.createToken(sessionId);
    });
  }

  createSession(sessionId) {
    return new Promise((resolve, reject) => {
      const body = JSON.stringify({ customSessionId: sessionId });
      const options = {
        headers: new HttpHeaders({
          Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + this.OPENVIDU_SERVER_SECRET),
          'Content-Type': 'application/json',
        }),
      };
      return this.httpClient
        .post(this.OPENVIDU_SERVER_URL + '/api/sessions', body, options)
        .pipe(
          catchError((error) => {
            if (error.status === 409) {
              resolve(sessionId);
            } else {
              console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + this.OPENVIDU_SERVER_URL);
              if (
                window.confirm(
                  'No connection to OpenVidu Server. This may be a certificate error at "' +
                    this.OPENVIDU_SERVER_URL +
                    '"\n\nClick OK to navigate and accept it. If no certificate warning is shown, then check that your OpenVidu Server' +
                    'is up and running at "' +
                    this.OPENVIDU_SERVER_URL +
                    '"',
                )
              ) {
                location.assign(this.OPENVIDU_SERVER_URL + '/accept-certificate');
              }
            }
            return observableThrowError(error);
          }),
        )
        .subscribe((response) => {
          console.log(response);
          resolve(response['id']);
        });
    });
  }

  createToken(sessionId): Promise<string> {
    return new Promise((resolve, reject) => {
      const body = JSON.stringify({ session: sessionId });
      const options = {
        headers: new HttpHeaders({
          Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + this.OPENVIDU_SERVER_SECRET),
          'Content-Type': 'application/json',
        }),
      };
      return this.httpClient
        .post(this.OPENVIDU_SERVER_URL + '/api/tokens', body, options)
        .pipe(
          catchError((error) => {
            reject(error);
            return observableThrowError(error);
          }),
        )
        .subscribe((response) => {
          console.log(response);
          resolve(response['token']);
        });
    });
  }

  ngOnInit() {
  }

}

打开-vidu.routing.ts

import { Routes } from '@angular/router';
import { OpenViduComponent } from './open-vidu.component';


export const OpenViduRoutes: Routes = [
  {
    path: '',
    component: OpenViduComponent
  }
];

打开-vidu.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { OpenViduComponent } from './open-vidu.component';
import { OpenViduRoutes } from './open-vidu.routing';

import { OpenviduSessionModule } from 'openvidu-angular';

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(OpenViduRoutes),
    FormsModule,
    OpenviduSessionModule
  ],
  declarations: [OpenViduComponent],
  exports: [
    OpenViduComponent
  ]
})
export class OpenViduModule {}

app.module.ts

...
import { OpenViduModule } from './open-vidu/open-vidu.module';
@NgModule({
    imports:      [
        CommonModule,
        BrowserAnimationsModule,
        FormsModule,
        RouterModule.forRoot(AppRoutes),
        HttpModule,
        MaterialModule,
        MatNativeDateModule,
        SidebarModule,
        NavbarModule,
        FooterModule,
        FixedpluginModule,
        HttpClientModule,
        OpenViduModule
    ],
    declarations: [
        AppComponent,
        AdminLayoutComponent,
        AuthLayoutComponent
    ],
    providers: [TwilioService, ChatService],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

我试图从app.module.ts中注释 openvidu 组件并将其导入子组件,但它不起作用并且一直抛出以下错误。 错误:RouterModule.forRoot() 调用了两次。 请建议我在代码中做错了什么。子模块代码如下:

导师模块.ts

...
import { OpenViduModule } from '../open-vidu/open-vidu.module';
@NgModule({
  imports: [
    ...,
    OpenViduModule
  ],
  providers: [TutorService],
  declarations: [
    AddTutorComponent,
    ListTutorComponent,
    EditTutorComponent,
    AllocateTutorComponent
  ]
})

export class Tutor {}

标签: angular

解决方案


推荐阅读