Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从angular service结果中正确取消订阅?_Javascript_Angular_Typescript_Rxjs - Fatal编程技术网

Javascript 如何从angular service结果中正确取消订阅?

Javascript 如何从angular service结果中正确取消订阅?,javascript,angular,typescript,rxjs,Javascript,Angular,Typescript,Rxjs,我在组件中有一个调用服务的方法,该服务返回一个可观察的 组件方法代码 public upload(file) { this.Service.ToBase64(files[0]) .subscribe(data => (this.convertedFile = data)); } 这很好,但当我取消订阅时,它就停止工作了 取消订阅-这不起作用 public upload(file) { this.Service.ToBase64(files[

我在组件中有一个调用服务的方法,该服务返回一个可观察的

组件方法代码

 public upload(file) { 
    this.Service.ToBase64(files[0])
        .subscribe(data => (this.convertedFile = data));
    }
这很好,但当我取消订阅时,它就停止工作了

取消订阅-这不起作用

 public upload(file) { 
    this.Service.ToBase64(files[0])
        .subscribe(data => (this.convertedFile = data)).Unsubscribe();
    }
服务代码方法

 convertedFile$: Subject<string> = new Subject<string>();

ToBase64(file: any) {
    const myReader = new FileReader();
    myReader.onloadend = e => {     
      this.convertedFile$.next(myReader.result.toString().split(',')[1]);
    };
    myReader.readAsDataURL(file);
    return this.convertedFile$.asObservable();
  }
convertedFile$:Subject=newsubject();
ToBase64(文件:任意){
const myReader=new FileReader();
myReader.onloadend=e=>{
这个.convertedFile$.next(myReader.result.toString().split(',')[1]);
};
myReader.readAsDataURL(文件);
返回此.convertedFile$.asObservable();
}

由于这是一个主题,我想退订。如何才能正确执行此操作?

您必须声明订阅属性

组件中的第一个

import { Subscription } from 'rxjs';
然后

在你的方法中

 public upload(file) { 
    this.fileSubscription = this.Service.ToBase64(files[0])
       .subscribe(data => (this.convertedFile = data));
    }
恩格德斯特罗法

ngOnDestroy() {
    if (this.fileSubscription) {
        this.fileSubscription.unsubscribe();
    }
}

关于方法是
unsubscribe()
而不是
unsubscribe()
。但是获得可观测值并销毁订阅的更优雅的方法是使用第一个操作符,如下所示:

import { first } from 'rxjs/operators';


  public upload(file) { 
    this.Service.ToBase64(files[0]).pipe(first())
        .subscribe(data => (this.convertedFile = data));
    }

我是新手,这是处理退订的最好方法吗?另外,这是从使用主题的服务中获得结果的最佳方式吗?我可以做一些更简单或更好的事情吗?还有其他的退订方式,但对我来说,这是最容易理解的方式。目前我没有使用Ngondestory方法取消订阅,我使用的是装饰器,但这需要更多关于Angular框架的知识。
import { first } from 'rxjs/operators';


  public upload(file) { 
    this.Service.ToBase64(files[0]).pipe(first())
        .subscribe(data => (this.convertedFile = data));
    }