ソースを参照

[angular demo] - first commit

kevin.song 6 年 前
コミット
c83f9707dc
33 ファイル変更1170 行追加0 行削除
  1. 13 0
      examples/angular/.editorconfig
  2. 53 0
      examples/angular/.gitignore
  3. 23 0
      examples/angular/README.md
  4. 125 0
      examples/angular/angular.json
  5. 12 0
      examples/angular/browserslist
  6. 32 0
      examples/angular/e2e/protractor.conf.js
  7. 23 0
      examples/angular/e2e/src/app.e2e-spec.ts
  8. 11 0
      examples/angular/e2e/src/app.po.ts
  9. 13 0
      examples/angular/e2e/tsconfig.json
  10. 32 0
      examples/angular/karma.conf.js
  11. 49 0
      examples/angular/package.json
  12. 8 0
      examples/angular/src/App.css
  13. 34 0
      examples/angular/src/App.ts
  14. 0 0
      examples/angular/src/assets/.gitkeep
  15. 13 0
      examples/angular/src/components/stream-player/index.css
  16. 15 0
      examples/angular/src/components/stream-player/index.html
  17. 168 0
      examples/angular/src/components/stream-player/index.ts
  18. 15 0
      examples/angular/src/config/README.md
  19. 3 0
      examples/angular/src/environments/environment.prod.ts
  20. 16 0
      examples/angular/src/environments/environment.ts
  21. BIN
      examples/angular/src/favicon.ico
  22. 13 0
      examples/angular/src/index.html
  23. 12 0
      examples/angular/src/main.ts
  24. 27 0
      examples/angular/src/pages/room/index.css
  25. 24 0
      examples/angular/src/pages/room/index.html
  26. 199 0
      examples/angular/src/pages/room/index.ts
  27. 63 0
      examples/angular/src/polyfills.ts
  28. 1 0
      examples/angular/src/styles.css
  29. 20 0
      examples/angular/src/test.ts
  30. 18 0
      examples/angular/tsconfig.app.json
  31. 26 0
      examples/angular/tsconfig.json
  32. 18 0
      examples/angular/tsconfig.spec.json
  33. 91 0
      examples/angular/tslint.json

+ 13 - 0
examples/angular/.editorconfig

@@ -0,0 +1,13 @@
+# Editor configuration, see https://editorconfig.org
+root = true
+
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 2
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.md]
+max_line_length = off
+trim_trailing_whitespace = false

+ 53 - 0
examples/angular/.gitignore

@@ -0,0 +1,53 @@
+# See http://help.github.com/ignore-files/ for more about ignoring files.
+
+# compiled output
+/dist
+/tmp
+/out-tsc
+# Only exists if Bazel was run
+/bazel-out
+
+# dependencies
+/node_modules
+
+# profiling files
+chrome-profiler-events*.json
+speed-measure-plugin*.json
+
+# IDEs and editors
+/.idea
+.project
+.classpath
+.c9/
+*.launch
+.settings/
+*.sublime-workspace
+
+# IDE - VSCode
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+.history/*
+
+# misc
+/.sass-cache
+/connect.lock
+/coverage
+/libpeerconnection.log
+npm-debug.log
+yarn-error.log
+testem.log
+/typings
+
+# System Files
+.DS_Store
+Thumbs.db
+
+
+yarn.lock
+package-lock.json
+
+# config
+src/config/index.ts

+ 23 - 0
examples/angular/README.md

@@ -0,0 +1,23 @@
+# URTC-demo(Angular 版本)
+
+## 运行步骤
+
+1. 添加配置
+
+详见 config 目录下的 README
+
+2. 安装 npm 依赖包
+
+```
+npm install
+```
+
+3. 执行运行命令
+
+```
+npm start
+```
+
+4. 打开页面
+
+浏览器打开 http://localhost:3000

+ 125 - 0
examples/angular/angular.json

@@ -0,0 +1,125 @@
+{
+  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
+  "version": 1,
+  "newProjectRoot": "projects",
+  "projects": {
+    "angular": {
+      "projectType": "application",
+      "schematics": {},
+      "root": "",
+      "sourceRoot": "src",
+      "prefix": "app",
+      "architect": {
+        "build": {
+          "builder": "@angular-devkit/build-angular:browser",
+          "options": {
+            "outputPath": "dist/angular",
+            "index": "src/index.html",
+            "main": "src/main.ts",
+            "polyfills": "src/polyfills.ts",
+            "tsConfig": "tsconfig.app.json",
+            "aot": false,
+            "assets": [
+              "src/favicon.ico",
+              "src/assets"
+            ],
+            "styles": [
+              "src/styles.css"
+            ],
+            "scripts": []
+          },
+          "configurations": {
+            "production": {
+              "fileReplacements": [
+                {
+                  "replace": "src/environments/environment.ts",
+                  "with": "src/environments/environment.prod.ts"
+                }
+              ],
+              "optimization": true,
+              "outputHashing": "all",
+              "sourceMap": false,
+              "extractCss": true,
+              "namedChunks": false,
+              "aot": true,
+              "extractLicenses": true,
+              "vendorChunk": false,
+              "buildOptimizer": true,
+              "budgets": [
+                {
+                  "type": "initial",
+                  "maximumWarning": "2mb",
+                  "maximumError": "5mb"
+                },
+                {
+                  "type": "anyComponentStyle",
+                  "maximumWarning": "6kb",
+                  "maximumError": "10kb"
+                }
+              ]
+            }
+          }
+        },
+        "serve": {
+          "builder": "@angular-devkit/build-angular:dev-server",
+          "options": {
+            "browserTarget": "angular:build"
+          },
+          "configurations": {
+            "production": {
+              "browserTarget": "angular:build:production"
+            }
+          }
+        },
+        "extract-i18n": {
+          "builder": "@angular-devkit/build-angular:extract-i18n",
+          "options": {
+            "browserTarget": "angular:build"
+          }
+        },
+        "test": {
+          "builder": "@angular-devkit/build-angular:karma",
+          "options": {
+            "main": "src/test.ts",
+            "polyfills": "src/polyfills.ts",
+            "tsConfig": "tsconfig.spec.json",
+            "karmaConfig": "karma.conf.js",
+            "assets": [
+              "src/favicon.ico",
+              "src/assets"
+            ],
+            "styles": [
+              "src/styles.css"
+            ],
+            "scripts": []
+          }
+        },
+        "lint": {
+          "builder": "@angular-devkit/build-angular:tslint",
+          "options": {
+            "tsConfig": [
+              "tsconfig.app.json",
+              "tsconfig.spec.json",
+              "e2e/tsconfig.json"
+            ],
+            "exclude": [
+              "**/node_modules/**"
+            ]
+          }
+        },
+        "e2e": {
+          "builder": "@angular-devkit/build-angular:protractor",
+          "options": {
+            "protractorConfig": "e2e/protractor.conf.js",
+            "devServerTarget": "angular:serve"
+          },
+          "configurations": {
+            "production": {
+              "devServerTarget": "angular:serve:production"
+            }
+          }
+        }
+      }
+    }},
+  "defaultProject": "angular"
+}

+ 12 - 0
examples/angular/browserslist

@@ -0,0 +1,12 @@
+# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
+# For additional information regarding the format and rule options, please see:
+# https://github.com/browserslist/browserslist#queries
+
+# You can see what browsers were selected by your queries by running:
+#   npx browserslist
+
+> 0.5%
+last 2 versions
+Firefox ESR
+not dead
+not IE 9-11 # For IE 9-11 support, remove 'not'.

+ 32 - 0
examples/angular/e2e/protractor.conf.js

@@ -0,0 +1,32 @@
+// @ts-check
+// Protractor configuration file, see link for more information
+// https://github.com/angular/protractor/blob/master/lib/config.ts
+
+const { SpecReporter } = require('jasmine-spec-reporter');
+
+/**
+ * @type { import("protractor").Config }
+ */
+exports.config = {
+  allScriptsTimeout: 11000,
+  specs: [
+    './src/**/*.e2e-spec.ts'
+  ],
+  capabilities: {
+    browserName: 'chrome'
+  },
+  directConnect: true,
+  baseUrl: 'http://localhost:4200/',
+  framework: 'jasmine',
+  jasmineNodeOpts: {
+    showColors: true,
+    defaultTimeoutInterval: 30000,
+    print: function() {}
+  },
+  onPrepare() {
+    require('ts-node').register({
+      project: require('path').join(__dirname, './tsconfig.json')
+    });
+    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
+  }
+};

+ 23 - 0
examples/angular/e2e/src/app.e2e-spec.ts

@@ -0,0 +1,23 @@
+import { AppPage } from './app.po';
+import { browser, logging } from 'protractor';
+
+describe('workspace-project App', () => {
+  let page: AppPage;
+
+  beforeEach(() => {
+    page = new AppPage();
+  });
+
+  it('should display welcome message', () => {
+    page.navigateTo();
+    expect(page.getTitleText()).toEqual('angular app is running!');
+  });
+
+  afterEach(async () => {
+    // Assert that there are no errors emitted from the browser
+    const logs = await browser.manage().logs().get(logging.Type.BROWSER);
+    expect(logs).not.toContain(jasmine.objectContaining({
+      level: logging.Level.SEVERE,
+    } as logging.Entry));
+  });
+});

+ 11 - 0
examples/angular/e2e/src/app.po.ts

@@ -0,0 +1,11 @@
+import { browser, by, element } from 'protractor';
+
+export class AppPage {
+  navigateTo() {
+    return browser.get(browser.baseUrl) as Promise<any>;
+  }
+
+  getTitleText() {
+    return element(by.css('app-root .content span')).getText() as Promise<string>;
+  }
+}

+ 13 - 0
examples/angular/e2e/tsconfig.json

@@ -0,0 +1,13 @@
+{
+  "extends": "../tsconfig.json",
+  "compilerOptions": {
+    "outDir": "../out-tsc/e2e",
+    "module": "commonjs",
+    "target": "es5",
+    "types": [
+      "jasmine",
+      "jasminewd2",
+      "node"
+    ]
+  }
+}

+ 32 - 0
examples/angular/karma.conf.js

@@ -0,0 +1,32 @@
+// Karma configuration file, see link for more information
+// https://karma-runner.github.io/1.0/config/configuration-file.html
+
+module.exports = function (config) {
+  config.set({
+    basePath: '',
+    frameworks: ['jasmine', '@angular-devkit/build-angular'],
+    plugins: [
+      require('karma-jasmine'),
+      require('karma-chrome-launcher'),
+      require('karma-jasmine-html-reporter'),
+      require('karma-coverage-istanbul-reporter'),
+      require('@angular-devkit/build-angular/plugins/karma')
+    ],
+    client: {
+      clearContext: false // leave Jasmine Spec Runner output visible in browser
+    },
+    coverageIstanbulReporter: {
+      dir: require('path').join(__dirname, './coverage/angular'),
+      reports: ['html', 'lcovonly', 'text-summary'],
+      fixWebpackSourcePaths: true
+    },
+    reporters: ['progress', 'kjhtml'],
+    port: 9876,
+    colors: true,
+    logLevel: config.LOG_INFO,
+    autoWatch: true,
+    browsers: ['Chrome'],
+    singleRun: false,
+    restartOnFileChange: true
+  });
+};

+ 49 - 0
examples/angular/package.json

@@ -0,0 +1,49 @@
+{
+  "name": "angular",
+  "version": "0.0.0",
+  "scripts": {
+    "ng": "ng",
+    "start": "ng serve",
+    "build": "ng build",
+    "test": "ng test",
+    "lint": "ng lint",
+    "e2e": "ng e2e"
+  },
+  "private": true,
+  "dependencies": {
+    "@angular/animations": "~8.2.14",
+    "@angular/common": "~8.2.14",
+    "@angular/compiler": "~8.2.14",
+    "@angular/core": "~8.2.14",
+    "@angular/forms": "~8.2.14",
+    "@angular/platform-browser": "~8.2.14",
+    "@angular/platform-browser-dynamic": "~8.2.14",
+    "@angular/router": "~8.2.14",
+    "rxjs": "~6.4.0",
+    "tslib": "^1.10.0",
+    "unique-classnames": "^1.0.6",
+    "urtc-sdk": "^1.4.5",
+    "zone.js": "~0.9.1"
+  },
+  "devDependencies": {
+    "@angular-devkit/build-angular": "~0.803.21",
+    "@angular/cli": "~8.3.21",
+    "@angular/compiler-cli": "~8.2.14",
+    "@angular/language-service": "~8.2.14",
+    "@types/jasmine": "~3.3.8",
+    "@types/jasminewd2": "~2.0.3",
+    "@types/node": "~8.9.4",
+    "codelyzer": "^5.0.0",
+    "jasmine-core": "~3.4.0",
+    "jasmine-spec-reporter": "~4.2.1",
+    "karma": "~4.1.0",
+    "karma-chrome-launcher": "~2.2.0",
+    "karma-coverage-istanbul-reporter": "~2.0.1",
+    "karma-jasmine": "~2.0.1",
+    "karma-jasmine-html-reporter": "^1.4.0",
+    "protractor": "~5.4.0",
+    "ts-node": "~7.0.0",
+    "tslint": "~5.15.0",
+    "typescript": "~3.5.3"
+  }
+}

+ 8 - 0
examples/angular/src/App.css

@@ -0,0 +1,8 @@
+.App {
+  margin-top: 60px;
+  font-family: 'Avenir', Helvetica, Arial, sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+  text-align: center;
+  color: #2c3e50;
+}

+ 34 - 0
examples/angular/src/App.ts

@@ -0,0 +1,34 @@
+import { BrowserModule } from '@angular/platform-browser';
+import { NgModule, Component } from '@angular/core';
+
+import { RoomComponent } from './pages/room';
+import { StreamPlayerComponent } from './components/stream-player';
+
+@Component({
+  selector: 'app-root',
+  template: `
+    <div class="App">
+      <app-room-page></app-room-page>
+      <br />
+      <a href="https://github.com/ucloud/urtc-sdk-web" target="_blank" rel="noopener noreferrer">
+        API 文档请看这里
+      </a>
+    </div>
+  `,
+  styleUrls: ['./App.css']
+})
+class AppComponent {}
+
+@NgModule({
+  declarations: [
+    StreamPlayerComponent,
+    RoomComponent,
+    AppComponent
+  ],
+  imports: [
+    BrowserModule
+  ],
+  providers: [],
+  bootstrap: [AppComponent]
+})
+export class AppModule { }

+ 0 - 0
examples/angular/src/assets/.gitkeep


+ 13 - 0
examples/angular/src/components/stream-player/index.css

@@ -0,0 +1,13 @@
+.media-player {
+  display: inline-block;
+  margin: 2px;
+  width: 300px;
+  text-align: left;
+  white-space: nowrap;
+  cursor: pointer;
+}
+
+.media-player video {
+  width: 100%;
+  height: 100%;
+}

+ 15 - 0
examples/angular/src/components/stream-player/index.html

@@ -0,0 +1,15 @@
+<div [class]="classes" (click)="handleClick()">
+  <div style="overflow: 'hidden'; text-overflow: 'ellipsis';">用户ID: {{stream.uid}}</div>
+  <div style="overflow: 'hidden'; text-overflow: 'ellipsis';">流ID: {{stream.sid}}</div>
+  <div [hidden]="!stream.mediaStream" style="overflow: 'hidden'; text-overflow: 'ellipsis';">
+    音量: {{volume}} %
+    &nbsp;&nbsp;&nbsp;&nbsp;音频丢包率: {{stats.audioLost}} %</div>
+  <div [hidden]="!stream.mediaStream" style="overflow: 'hidden'; text-overflow: 'ellipsis';">视频丢包率: {{stats.videoLost}}
+    %
+    &nbsp;&nbsp;&nbsp;&nbsp;网络延时: {{stats.rtt}} ms</div>
+  <div [hidden]="!stream.mediaStream">
+    <video webkit-playsinline autoplay playsinline #video>
+    </video>
+  </div>
+  <p [hidden]="stream.mediaStream">unsubscribe</p>
+</div>

+ 168 - 0
examples/angular/src/components/stream-player/index.ts

@@ -0,0 +1,168 @@
+import {
+  Component,
+  OnInit,
+  AfterViewInit,
+  OnChanges,
+  OnDestroy,
+  Input,
+  SimpleChanges,
+  ViewChild,
+  ElementRef
+} from '@angular/core';
+import classnames from 'unique-classnames';
+
+import { Client } from 'urtc-sdk';
+import { Stream, AudioStats, VideoStats, NetworkStats } from '../../../../../types/index.d';
+
+interface Stats {
+  audioLost: number;
+  biggestAudioLost: number;
+  videoLost: number;
+  biggestVideoLost: number;
+  rtt: number;
+  biggestRTT: number;
+}
+
+@Component({
+  selector: 'app-stream-player',
+  templateUrl: './index.html',
+  styleUrls: ['./index.css']
+})
+export class StreamPlayerComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit {
+  @Input() className: string;
+  @Input() stream: Stream;
+  @Input() client: Client;
+  @Input() onClick: (stream: Stream) => void;
+
+  private classes: string;
+  private volume = 0;
+  private stats: Stats = {
+    audioLost: 0,
+    biggestAudioLost: 0,
+    videoLost: 0,
+    biggestVideoLost: 0,
+    rtt: 0,
+    biggestRTT: 0
+  };
+
+  private volumeTimer: number;
+  private stateTimer: number;
+
+  @ViewChild('video', {static: true}) videoRef: ElementRef;
+
+  private isComponentDestroyed: boolean;
+
+  constructor() {
+    this.volumeTimer = 0;
+    this.stateTimer = 0;
+  }
+
+  ngOnInit() {
+    this.classes = classnames('media-player', this.className);
+    this.isComponentDestroyed = false;
+  }
+
+  ngOnChanges(changes: SimpleChanges) {
+    const { stream } = changes;
+    const currentValue: Stream = stream.currentValue;
+    const previousValue: Stream = stream.previousValue;
+    if (stream.firstChange && currentValue.mediaStream) {
+      this.play(currentValue.mediaStream);
+      return;
+    }
+    if (!currentValue.mediaStream) {
+      this.stop();
+    } else if (currentValue.mediaStream !== previousValue.mediaStream) {
+      this.play(currentValue.mediaStream);
+    }
+  }
+
+  ngAfterViewInit() {
+    if (this.stream.mediaStream) {
+      this.play(this.stream.mediaStream);
+    }
+  }
+
+  ngOnDestroy() {
+    this.stop();
+    this.isComponentDestroyed = true;
+  }
+
+  play(mediaStream: MediaStream) {
+    this.videoRef.nativeElement.srcObject = mediaStream;
+    this.startGetVolume();
+    this.startGetState();
+  }
+  stop() {
+    this.stopGetVolume();
+    this.stopGetState();
+    this.videoRef.nativeElement.srcObject = null;
+  }
+
+  startGetVolume() {
+    const { client, stream } = this;
+    if (!client || !stream || !stream.audio) {
+      return;
+    }
+    if (this.volumeTimer) {
+      window.clearInterval(this.volumeTimer);
+    }
+    this.volumeTimer = window.setInterval(() => {
+      this.volume = client.getAudioVolume(stream.sid);
+    }, 1000);
+  }
+  stopGetVolume() {
+    window.clearInterval(this.volumeTimer);
+  }
+  startGetState() {
+    const { client, stream } = this;
+    if (!client || !stream || !stream.video) {
+      return;
+    }
+    if (this.stateTimer) {
+      window.clearInterval(this.stateTimer);
+    }
+    this.stateTimer = window.setInterval(() => {
+      client.getAudioStats(stream.sid, (pstats: AudioStats) => {
+        // if (this.isComponentDestroyed) return;
+        const { stats } = this;
+        stats.audioLost = pstats.lostpre;
+        if (stats.biggestAudioLost < pstats.lostpre) {
+          stats.biggestAudioLost = pstats.lostpre;
+        }
+      }, (e) => {
+        console.error('get video stats ', stream.sid);
+      });
+      client.getVideoStats(stream.sid, (pstats: VideoStats) => {
+        // if (this.isComponentDestroyed) return;
+        const { stats } = this;
+        stats.videoLost = pstats.lostpre;
+        if (stats.biggestVideoLost < pstats.lostpre) {
+          stats.biggestVideoLost = pstats.lostpre;
+        }
+      }, (e) => {
+        console.error('get video stats ', stream.sid);
+      });
+      client.getNetworkStats(stream.sid, (pstats: NetworkStats) => {
+        // if (this.isComponentDestroyed) return;
+        const { stats } = this;
+        stats.rtt = pstats.rtt;
+        if (stats.biggestRTT < pstats.rtt) {
+          stats.biggestRTT = pstats.rtt;
+        }
+      }, (e) => {
+        console.error('get network stats ', stream.sid);
+      });
+    }, 1000);
+  }
+  stopGetState() {
+    window.clearInterval(this.stateTimer);
+  }
+  handleClick() {
+    console.log('click ', this);
+    const { stream, onClick } = this;
+    if (onClick) {
+      onClick(stream);
+    }
+  }
+}

+ 15 - 0
examples/angular/src/config/README.md

@@ -0,0 +1,15 @@
+本目录中需要创建 index.ts 文件,并配置 AppId 和 AppKey,示例代码:
+
+```
+const config = {
+  AppId: 'urtc-xxxxxxxx',
+  AppKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
+}
+
+export default config;
+```
+
+> 注:
+> 
+> 1. AppId 和 AppKey 可从 URTC 产品中获取
+> 2. AppKey 不可暴露于公网,建议生产环境时,由后端进行保存并由前端调 API 获取

+ 3 - 0
examples/angular/src/environments/environment.prod.ts

@@ -0,0 +1,3 @@
+export const environment = {
+  production: true
+};

+ 16 - 0
examples/angular/src/environments/environment.ts

@@ -0,0 +1,16 @@
+// This file can be replaced during build by using the `fileReplacements` array.
+// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
+// The list of file replacements can be found in `angular.json`.
+
+export const environment = {
+  production: false
+};
+
+/*
+ * For easier debugging in development mode, you can import the following file
+ * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
+ *
+ * This import should be commented out in production mode because it will have a negative impact
+ * on performance if an error is thrown.
+ */
+// import 'zone.js/dist/zone-error';  // Included with Angular CLI.

BIN
examples/angular/src/favicon.ico


+ 13 - 0
examples/angular/src/index.html

@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>URTC Demo</title>
+  <base href="/">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+  <link rel="icon" type="image/x-icon" href="favicon.ico">
+</head>
+<body>
+  <app-root></app-root>
+</body>
+</html>

+ 12 - 0
examples/angular/src/main.ts

@@ -0,0 +1,12 @@
+import { enableProdMode } from '@angular/core';
+import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
+
+import { AppModule } from './App';
+import { environment } from './environments/environment';
+
+if (environment.production) {
+  enableProdMode();
+}
+
+platformBrowserDynamic().bootstrapModule(AppModule)
+  .catch(err => console.error(err));

+ 27 - 0
examples/angular/src/pages/room/index.css

@@ -0,0 +1,27 @@
+.room {
+  max-width: 640px;
+  margin: 0 auto;
+}
+
+.room .local-stream,
+.room .remote-stream {
+  text-align: left;
+}
+
+.room button {
+  padding: 8px 0;
+  display: inline-block;
+  width: 100%;
+  border-radius: 6px;
+  cursor: pointer;
+  text-align: center;
+  ;
+}
+
+.room input:visited,
+.room button:focus,
+.room button:visited,
+.room button:hover,
+.room button:active {
+  outline: none;
+}

+ 24 - 0
examples/angular/src/pages/room/index.html

@@ -0,0 +1,24 @@
+<div class="room">
+  <label>房间号:{{roomId}}({{roomStatus}})</label>
+  <p>当前选中的流:{{selectedStreamStatus}}</p>
+  <h3>本地(发布)流</h3>
+  <app-stream-player *ngFor="let stream of localStreams"
+    className="local-stream"
+    [stream]="stream"
+    [client]="client"
+    [onClick]="onSelectStream"></app-stream-player>
+  <h3>远端(订阅)流</h3>
+  <app-stream-player *ngFor="let stream of remoteStreams"
+    className="remote-stream"
+    [stream]="stream"
+    [client]="client"
+    [onClick]="onSelectStream"></app-stream-player>
+  <h3>操作</h3>
+  <button (click)="handleJoinRoom()">加入房间</button>
+  <button (click)="handlePublish()">发布</button>
+  <button (click)="handlePublishScreen()">屏幕共享</button>
+  <button (click)="handleUnpublish()">取消发布/屏幕共享</button>
+  <button (click)="handleSubscribe()">订阅</button>
+  <button (click)="handleUnsubscribe()">取消订阅</button>
+  <button (click)="handleLeaveRoom()">离开房间</button>
+</div>

+ 199 - 0
examples/angular/src/pages/room/index.ts

@@ -0,0 +1,199 @@
+import {
+  Component,
+  OnInit,
+  AfterContentInit,
+  AfterViewInit,
+  OnDestroy,
+} from '@angular/core';
+
+import sdk, { Client } from 'urtc-sdk';
+import { Stream } from '../../../../../types';
+import config from '../../config';
+
+const { AppId, AppKey } = config;
+
+// 此处使用固定的房间号的随机的用户ID,请自行替换
+const RoomId = 'ssss02';
+const UserId = Math.floor(Math.random() * 1000000).toString();
+
+console.log('UCloudRTC sdk version: ', sdk.version);
+
+@Component({
+  selector: 'app-room-page',
+  templateUrl: './index.html',
+  styleUrls: ['./index.css']
+})
+export class RoomComponent implements OnInit, AfterContentInit, AfterViewInit, OnDestroy {
+  private client: Client;
+  private roomId: string = RoomId;
+  private userId: string = UserId;
+  private isJoinedRoom = false;
+  private selectedStream: Stream | null = null;
+  private localStreams: Stream[] = [];
+  private remoteStreams: Stream[] = [];
+
+  get roomStatus() {
+    return this.isJoinedRoom ? '已加入' : '未加入';
+  }
+  get selectedStreamStatus() {
+    return this.selectedStream ? this.selectedStream.sid : '未选择';
+  }
+
+  private leaveRoom: () => void;
+  private onSelectStream: () => void;
+
+  ngOnInit() {
+    if (!AppId || !AppKey) {
+      alert('请先设置 AppId 和 AppKey');
+      return;
+    }
+    if (!RoomId) {
+      alert('请先设置 RoomId');
+      return;
+    }
+    if (!UserId) {
+      alert('请先设置 UserId');
+    }
+    this.leaveRoom = this.handleLeaveRoom.bind(this);
+    this.onSelectStream = this.handleSelectStream.bind(this);
+  }
+
+  ngAfterContentInit() {
+    const token = sdk.generateToken(AppId, AppKey, RoomId, UserId);
+    this.client = new Client(AppId, token);
+    this.client.on('stream-published', (localStream) => {
+      console.info('stream-published: ', localStream);
+      const { localStreams } = this;
+      localStreams.push(localStream);
+    });
+    this.client.on('stream-added', (remoteStream) => {
+      console.info('stream-added: ', remoteStream);
+      const { remoteStreams } = this;
+      remoteStreams.push(remoteStream);
+      // 自动订阅
+      this.client.subscribe(remoteStream.sid, (err) => {
+        console.error('自动订阅失败:', err);
+      });
+    });
+    this.client.on('stream-subscribed', (remoteStream) => {
+      console.info('stream-subscribed: ', remoteStream);
+      const { remoteStreams } = this;
+      const idx = remoteStreams.findIndex(item => item.sid === remoteStream.sid);
+      if (idx >= 0) {
+        remoteStreams.splice(idx, 1, remoteStream);
+      }
+    });
+    this.client.on('stream-removed', (remoteStream) => {
+      console.info('stream-removed: ', remoteStream);
+      const { remoteStreams } = this;
+      const idx = remoteStreams.findIndex(item => item.sid === remoteStream.sid);
+      if (idx >= 0) {
+        remoteStreams.splice(idx, 1);
+      }
+    });
+
+    window.addEventListener('beforeunload', this.leaveRoom);
+  }
+
+  ngAfterViewInit() {
+    console.log('view inited, todo something');
+  }
+
+  ngOnDestroy() {
+    console.info('component will destroy');
+    window.removeEventListener('beforeunload', this.leaveRoom);
+    this.handleLeaveRoom();
+  }
+
+  handleJoinRoom() {
+    const { roomId, userId, isJoinedRoom } = this;
+    if (isJoinedRoom) {
+      alert('已经加入了房间');
+      return;
+    }
+    if (!roomId) {
+      alert('请先填写房间号');
+      return;
+    }
+    this.client.joinRoom(roomId, userId, () => {
+      console.info('加入房间成功');
+      this.isJoinedRoom = true;
+    }, (err) => {
+      console.error('加入房间失败: ', err);
+    });
+  }
+  handlePublish() {
+    this.client.publish(err => {
+      console.error('发布失败:', err);
+    });
+  }
+  handlePublishScreen() {
+    this.client.publish({ audio: true, video: false, screen: true }, (err) => {
+      console.error('发布失败:', err);
+    });
+  }
+  handleUnpublish() {
+    const { selectedStream } = this;
+    if (!selectedStream) {
+      alert('未选择需要取消发布的本地流');
+      return;
+    }
+    this.client.unpublish(selectedStream.sid, (stream) => {
+      console.info('取消发布本地流成功:', stream);
+      const { localStreams } = this;
+      const idx = localStreams.findIndex(item => item.sid === stream.sid);
+      if (idx >= 0) {
+        localStreams.splice(idx, 1);
+      }
+      this.selectedStream = null;
+    }, (err) => {
+      console.error('取消发布本地流失败:', err);
+    });
+  }
+  handleSubscribe() {
+    const { selectedStream } = this;
+    if (!selectedStream) {
+      alert('未选择需要订阅的远端流');
+      return;
+    }
+    this.client.subscribe(selectedStream.sid, (err) => {
+      console.error('订阅失败:', err);
+    });
+  }
+  handleUnsubscribe() {
+    const { selectedStream } = this;
+    if (!selectedStream) {
+      alert('未选择需要取消订阅的远端流');
+      return;
+    }
+    this.client.unsubscribe(selectedStream.sid, (stream) => {
+      console.info('取消订阅成功:', stream);
+      const { remoteStreams } = this;
+      const idx = remoteStreams.findIndex(item => item.sid === stream.sid);
+      if (idx >= 0) {
+        remoteStreams.splice(idx, 1, stream);
+      }
+    }, (err) => {
+      console.error('订阅失败:', err);
+    });
+  }
+  handleLeaveRoom() {
+    const { isJoinedRoom } = this;
+    if (!isJoinedRoom) {
+      return;
+    }
+    this.client.leaveRoom(() => {
+      console.info('离开房间成功');
+      this.selectedStream = null;
+      this.localStreams = [];
+      this.remoteStreams = [];
+      this.isJoinedRoom = false;
+    }, (err) => {
+      console.error('离开房间失败:', err);
+    });
+  }
+  handleSelectStream(stream) {
+    console.log('select stream: ', stream);
+    this.selectedStream = stream;
+  }
+}

+ 63 - 0
examples/angular/src/polyfills.ts

@@ -0,0 +1,63 @@
+/**
+ * This file includes polyfills needed by Angular and is loaded before the app.
+ * You can add your own extra polyfills to this file.
+ *
+ * This file is divided into 2 sections:
+ *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
+ *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
+ *      file.
+ *
+ * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
+ * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
+ * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
+ *
+ * Learn more in https://angular.io/guide/browser-support
+ */
+
+/***************************************************************************************************
+ * BROWSER POLYFILLS
+ */
+
+/** IE10 and IE11 requires the following for NgClass support on SVG elements */
+// import 'classlist.js';  // Run `npm install --save classlist.js`.
+
+/**
+ * Web Animations `@angular/platform-browser/animations`
+ * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
+ * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
+ */
+// import 'web-animations-js';  // Run `npm install --save web-animations-js`.
+
+/**
+ * By default, zone.js will patch all possible macroTask and DomEvents
+ * user can disable parts of macroTask/DomEvents patch by setting following flags
+ * because those flags need to be set before `zone.js` being loaded, and webpack
+ * will put import in the top of bundle, so user need to create a separate file
+ * in this directory (for example: zone-flags.ts), and put the following flags
+ * into that file, and then add the following code before importing zone.js.
+ * import './zone-flags.ts';
+ *
+ * The flags allowed in zone-flags.ts are listed here.
+ *
+ * The following flags will work for all browsers.
+ *
+ * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
+ * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
+ * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
+ *
+ *  in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
+ *  with the following flag, it will bypass `zone.js` patch for IE/Edge
+ *
+ *  (window as any).__Zone_enable_cross_context_check = true;
+ *
+ */
+
+/***************************************************************************************************
+ * Zone JS is required by default for Angular itself.
+ */
+import 'zone.js/dist/zone';  // Included with Angular CLI.
+
+
+/***************************************************************************************************
+ * APPLICATION IMPORTS
+ */

+ 1 - 0
examples/angular/src/styles.css

@@ -0,0 +1 @@
+/* You can add global styles to this file, and also import other style files */

+ 20 - 0
examples/angular/src/test.ts

@@ -0,0 +1,20 @@
+// This file is required by karma.conf.js and loads recursively all the .spec and framework files
+
+import 'zone.js/dist/zone-testing';
+import { getTestBed } from '@angular/core/testing';
+import {
+  BrowserDynamicTestingModule,
+  platformBrowserDynamicTesting
+} from '@angular/platform-browser-dynamic/testing';
+
+declare const require: any;
+
+// First, initialize the Angular testing environment.
+getTestBed().initTestEnvironment(
+  BrowserDynamicTestingModule,
+  platformBrowserDynamicTesting()
+);
+// Then we find all the tests.
+const context = require.context('./', true, /\.spec\.ts$/);
+// And load the modules.
+context.keys().map(context);

+ 18 - 0
examples/angular/tsconfig.app.json

@@ -0,0 +1,18 @@
+{
+  "extends": "./tsconfig.json",
+  "compilerOptions": {
+    "outDir": "./out-tsc/app",
+    "types": []
+  },
+  "files": [
+    "src/main.ts",
+    "src/polyfills.ts"
+  ],
+  "include": [
+    "src/**/*.ts"
+  ],
+  "exclude": [
+    "src/test.ts",
+    "src/**/*.spec.ts"
+  ]
+}

+ 26 - 0
examples/angular/tsconfig.json

@@ -0,0 +1,26 @@
+{
+  "compileOnSave": false,
+  "compilerOptions": {
+    "baseUrl": "./",
+    "outDir": "./dist/out-tsc",
+    "sourceMap": true,
+    "declaration": false,
+    "downlevelIteration": true,
+    "experimentalDecorators": true,
+    "module": "esnext",
+    "moduleResolution": "node",
+    "importHelpers": true,
+    "target": "es2015",
+    "typeRoots": [
+      "node_modules/@types"
+    ],
+    "lib": [
+      "es2018",
+      "dom"
+    ]
+  },
+  "angularCompilerOptions": {
+    "fullTemplateTypeCheck": true,
+    "strictInjectionParameters": true
+  }
+}

+ 18 - 0
examples/angular/tsconfig.spec.json

@@ -0,0 +1,18 @@
+{
+  "extends": "./tsconfig.json",
+  "compilerOptions": {
+    "outDir": "./out-tsc/spec",
+    "types": [
+      "jasmine",
+      "node"
+    ]
+  },
+  "files": [
+    "src/test.ts",
+    "src/polyfills.ts"
+  ],
+  "include": [
+    "src/**/*.spec.ts",
+    "src/**/*.d.ts"
+  ]
+}

+ 91 - 0
examples/angular/tslint.json

@@ -0,0 +1,91 @@
+{
+  "extends": "tslint:recommended",
+  "rules": {
+    "array-type": false,
+    "arrow-parens": false,
+    "deprecation": {
+      "severity": "warning"
+    },
+    "component-class-suffix": true,
+    "contextual-lifecycle": true,
+    "directive-class-suffix": true,
+    "directive-selector": [
+      true,
+      "attribute",
+      "app",
+      "camelCase"
+    ],
+    "component-selector": [
+      true,
+      "element",
+      "app",
+      "kebab-case"
+    ],
+    "import-blacklist": [
+      true,
+      "rxjs/Rx"
+    ],
+    "interface-name": false,
+    "max-classes-per-file": false,
+    "max-line-length": [
+      true,
+      140
+    ],
+    "member-access": false,
+    "member-ordering": [
+      true,
+      {
+        "order": [
+          "static-field",
+          "instance-field",
+          "static-method",
+          "instance-method"
+        ]
+      }
+    ],
+    "no-consecutive-blank-lines": false,
+    "no-console": [
+      false,
+      "debug",
+      "info",
+      "time",
+      "timeEnd",
+      "trace"
+    ],
+    "no-empty": false,
+    "no-inferrable-types": [
+      true,
+      "ignore-params"
+    ],
+    "no-non-null-assertion": true,
+    "no-redundant-jsdoc": true,
+    "no-switch-case-fall-through": true,
+    "no-var-requires": false,
+    "object-literal-key-quotes": [
+      true,
+      "as-needed"
+    ],
+    "object-literal-sort-keys": false,
+    "ordered-imports": false,
+    "quotemark": [
+      true,
+      "single"
+    ],
+    "trailing-comma": false,
+    "no-conflicting-lifecycle": true,
+    "no-host-metadata-property": true,
+    "no-input-rename": true,
+    "no-inputs-metadata-property": true,
+    "no-output-native": true,
+    "no-output-on-prefix": true,
+    "no-output-rename": true,
+    "no-outputs-metadata-property": true,
+    "template-banana-in-box": true,
+    "template-no-negated-async": true,
+    "use-lifecycle-interface": true,
+    "use-pipe-transform-interface": true
+  },
+  "rulesDirectory": [
+    "codelyzer"
+  ]
+}