4

只是我用 Angular2 RC3(使用 Angular-CLI)尝试了我的第一个应用程序,但我迷失了这个......

我对变量的“更改检测”有疑问word。我更新了Observable 方法中的word变量subscribe,但没有检测到任何变化。

app.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { VoiceRecognitionService } from './voice-recognition.service';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  template: `<h1>{{word}}</h1>`, // => No prints any update
  providers: [VoiceRecognitionService],
  styleUrls: ['app.component.css']
})
export class AppComponent implements OnInit {

  private voice: VoiceRecognitionService;
  public word: string = '';

  constructor( @Inject(VoiceRecognitionService) voiceRecognition: VoiceRecognitionService) {
    this.voice = voiceRecognition;
  }

  ngOnInit() {
    this.voice.record('ca')
      .subscribe(word => {
        console.log(word); // => Is printing well the new word
        this.word = `${word}...`; // => No changes detected
      });
  }
}

我记得在 Angular 1 中$scope.$apply对类似情况的使用,我在 Angular2 中搜索相同,我发现NgZone.run,我试图在里面执行NgZone.run,但什么也没有。

我做错了什么?

非常感谢。


额外的:

我与 Observable 分享我的服务:

语音识别.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';

export interface IWindow extends Window {
  webkitSpeechRecognition: any;
}

@Injectable()
export class VoiceRecognitionService {

  constructor() {
    /* void */
  }

  /**
   * Record
   * @param {string} language - Language of the voice recognition
   * @returns {Observable<string>} - Observable of voice converted to string 
   */
  record(language: string): Observable<string> {
    return Observable.create((observer) => {
      const { webkitSpeechRecognition }: IWindow = <IWindow>window;
      const recognition = new webkitSpeechRecognition();

      recognition.onresult = (e) => observer.next(e.results.item(e.results.length - 1).item(0).transcript);
      recognition.onerror = observer.error;
      recognition.onend = observer.completed;

      recognition.continuous = true;
      recognition.interimResults = true;
      recognition.lang = language;
      recognition.start();
    });
  }
}
4

2 回答 2

10

我假设webkitSpeechRecognitionAPI 没有被 Angulars zone 修补。

要解决使用zone.run(...)强制执行回到 Angulars 区域的问题:

@Injectable()
export class VoiceRecognitionService {

  constructor(private zone:NgZone) {
    /* void */
  }

  /**
   * Record
   * @param {string} language - Language of the voice recognition
   * @returns {Observable<string>} - Observable of voice converted to string 
   */
  record(language: string): Observable<string> {
    return Observable.create((observer) => {
      const { webkitSpeechRecognition }: IWindow = <IWindow>window;
      const recognition = new webkitSpeechRecognition();

      recognition.onresult = (e) => this.zone.run(() => observer.next(e.results.item(e.results.length - 1).item(0).transcript));
      recognition.onerror = (e) => this.zone.run(() => observer.error(e));
      recognition.onend = (e) => this.zone.run(() => observer.completed(e));

      recognition.continuous = true;
      recognition.interimResults = true;
      recognition.lang = language;
      recognition.start();
    });
  }
}

如果回调需要不同数量的参数 ( (e)),请相应地调整代码。我只是为每个假设一个参数。

这种方法的优点是该服务的用户不必采取额外的措施。

于 2016-06-29T12:56:35.497 回答
0

您最终可以显式调用该类的detectChanges方法ChangeDetectorRef

constructor( @Inject(VoiceRecognitionService) voiceRecognition: VoiceRecognitionService,
    private cdr:ChangeDetectorRef) {
  this.voice = voiceRecognition;
}

ngOnInit() {
  this.voice.record('ca')
    .subscribe(word => {
      console.log(word); // => Is printing well the new word
      this.word = `${word}...`; // => No changes detected
      this.cdr.detectChanges(); // <---------
    });
}
于 2016-06-29T12:57:56.020 回答