找不到名字onUnsubscribe

时间:2017-11-27 03:23:13

标签: angular rxjs

出现此错误Cannot find name onUnsubscribe

我应该导入什么?

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

@Component({
    selector: 'app',
    template: `
      <b>Angular 2 Component Using Observables!</b>

      <h5 style="margin-bottom: 0">VALUES</h5>
      <pre><code>{{value}}</code></pre>

      <h5 style="margin-bottom: 0">SUBSCRIBED</h5>
      <pre><code>{{subscribed}}</code></pre>

      <h5 style="margin-bottom: 0">STATUS</h5>
      <pre><code>{{status}}</code></pre>

      <button style="margin-top: 2rem" (click)="init()">Init</button>
  `
})
export class MyApp {

  private data: Observable<string>;
  private value: string;
  private subscribed: boolean;
  private status: string;

    init() {

        this.data = new Observable(observer => {
            let timeoutId = setTimeout(() => {
                observer.next('You will never see this message');
            }, 2000);

            this.status = 'Started';

            return onUnsubscribe = () => {
                this.subscribed = false;
                this.status = 'Finished';
                clearTimeout(timeoutId);
            }
        });

        let subscription = this.data.subscribe(
            value => this.value = value,
            error => console.log(error),
            () => this.status = 'Finished';
        );
        this.subscribed = true;

        setTimeout(() => {
          subscription.unsubscribe();
        }, 1000);
    }

}

http://plnkr.co/edit/0MfW5d?p=preview

当时看来ng2非常不同。我认为数据应该是Observable<string>。我不知道为什么plnkr代码有效。

这个onUnsubscribe是一种自定义回调。

1 个答案:

答案 0 :(得分:0)

因为没有类型检查,所以可以使用吸管。

您不必(不应该)为返回功能命名。 Observable将在完成后调用它们的返回函数。

return () => {
    this.subscribed = false;
    this.status = 'Finished';
    clearTimeout(timeoutId);
}

更新了Plunker:http://plnkr.co/edit/u7vbcY?p=preview