下面是一个组件的代码. ts在角度和我得到下面的erro编译问题:X
错误
merge/merge.组件. ts:75:12-错误TS2551:“可观察”类型上不存在属性“取消订阅”。你是说“订阅”吗?
75出$().退订() ~~~~~~~~~~~
…/…/node_modules/rxjs/dist/类型/内部/可观察. d.ts:53:5 53订阅(观察者?:部分
import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { defer, Observable, of, Subscription } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import {filter,map,distinctUntilChanged,distinctUntilKeyChanged, mergeAll, mergeMap, concatAll, retry, repeat} from 'rxjs/operators'
import {from} from 'rxjs';
@Component({
selector: 'app-merge',
templateUrl: './merge.component.html',
styleUrls: ['./merge.component.scss']
})
export class MergeComponent implements OnInit {
public items:any[]=[];
constructor(private http: HttpClient){}
ngOnInit(): void {
let counter=1;
const out$=()=> defer(()=>this.http.get('https://jsonplaceholder.typicode.com/todos/'+counter++)).pipe(
repeat(4)
);
out$().subscribe(
data => console.log(data)
)
out$().unsubscribe()
}
}
订阅()方法返回一个Subspse tion,你必须取消订阅。为了使其更有用,您应该将其存储并在ngOnDestroy中取消订阅此订阅:
export class MergePageComponent implements OnInit, OnDestroy {
protected mySubscription: Subscription;
constructor( )
ngOnInit(): void {
...
this.mySubscription = out$().subscribe(
data => console.log(data)
);
}
ngOnDestroy(): void {
this.mySubscription.unsubscribe();
}
可观察对象没有取消订阅方法。当您订阅可观察对象时,它会为您提供订阅。然后您可以取消订阅订阅。
const mySubscription = out$().subscribe(
data => console.log(data)
);
mySubscription.unsubscribe();