gpt4 book ai didi

rxjs5 - 是否可以将 Teardown 逻辑添加到已经存在的 Observable 中?

转载 作者:行者123 更新时间:2023-12-05 00:54:51 24 4
gpt4 key购买 nike

例如,我目前正在调用从 Angular 2 的 HTTP 返回的 Observable 的取消订阅。

但是我有一些围绕它的自定义逻辑。

是否可以向已经存在的 Observable 添加自定义拆卸逻辑,例如从 Angular 2 的 HTTP 返回的那个?

可能类似于 Observable.prototype.whenUnsubscribed(customTeardownLogic) 的东西?

最佳答案

这可能不是您想要的,但它可能会有所帮助:
假设你有这样的东西(取自 Angular 2 网站的 the Hero Guide):

@Injectable()
export class HeroService {
private heroesUrl = 'api/heroes'; // URL to web API

constructor (private http: Http) {}

getHeroes(): Observable<Hero[]> {
return this.http
.get(this.heroesUrl)
.map(this.extractData);
}

private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
}

// Somewhere else in your code you do:
let subscription = service.getHeroes().subscribe(/* do stuff here */);

// ...and later on:
subscription.unsubscribe();
如果你想添加一些自定义的拆卸逻辑,你可以用你自己的包装 Angular 2 返回的 Observable:
getHeroes(): Observable<Hero[]> {
return Observable.create(
//Let's provide a subscribe function
(observer: any) => {
const subscription = this.http
.get(this.heroesUrl)
.map(this.extractData)
.subscribe(observer);

// Return a tear-down/unsubscribe function
return () => {
subscription.unsubscribe();
this.myTearDownLogic();
}
}
);
}

关于rxjs5 - 是否可以将 Teardown 逻辑添加到已经存在的 Observable 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39115006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com