有几种方法可以取消订阅 Angular 组件上的 observables(通过使用 ngOnDestroy)。应首选以下哪个选项?为什么(例如技术原因、性能等)?
使用 RxJS takeUntil 取消订阅
@Component({
selector: "app-flights",
templateUrl: "./flights.component.html"
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) {}
ngOnInit() {
this.flightService
.getAll()
.pipe(takeUntil(this.destroy$))
.subscribe(flights => (this.flights = flights));
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
Run Code Online (Sandbox Code Playgroud)
显式调用 .unsubscribe(),例如通过使用单独的订阅实例
@Component({
selector: "app-flights",
templateUrl: "./flights.component.html"
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly subscriptions = new Subscription();
public flights: …Run Code Online (Sandbox Code Playgroud) 在 Angular 7 组件中,我使用 RxJS takeUntil() 正确取消订阅可观察订阅。
this.destroy$.next()方法中缺少时会发生什么ngOnDestroy(参见下面的示例)?它仍然会正常退订吗?this.destroy$.complete()方法中缺少时会发生什么ngOnDestroy(参见下面的示例)?它仍然会正常退订吗?
@Component({
selector: 'app-flights',
templateUrl: './flights.component.html'
})
export class FlightsComponent implements OnDestroy, OnInit {
private readonly destroy$ = new Subject();
public flights: FlightModel[];
constructor(private readonly flightService: FlightService) { }
ngOnInit() {
this.flightService.getAll()
.pipe(takeUntil(this.destroy$))
.subscribe(flights => this.flights = flights);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
Run Code Online (Sandbox Code Playgroud) 什么时候asObservable()需要一个主题(例如 BehaviorSubject)来获得该主题的可观察性?主题 isself 也可以转换为 Observable。
name1$和之间的技术区别是name2$什么?name1$或name2$)?import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs';
export class Person {
private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');
public get name1$(): Observable<string> {
return this.nameSubject.asObservable();
}
public get name2$(): Observable<string> {
return this.nameSubject;
}
public setName(value: string): void {
this.nameSubject.next(value);
}
}
Run Code Online (Sandbox Code Playgroud)
提前感谢您的回答!
我的应用程序报告它已加载一个名为“Microsoft.GeneratedCode”的程序集。我想验证我的应用程序或程序集的哪个部分正在生成此特定程序集。该程序集仅加载一次。
有关加载的程序集的详细信息:
通常,我的应用程序通过使用 Apache.NMS 1.7.0.3635、Apache.NMS.ActiveMQ 1.7.0.3660 连接到 Apache ActiveMQ,另一方面,我的应用程序处理包含序列化模型 (XML) 的 HTTPS 请求/响应。
在我的研究中,我找到了答案,这表明程序集“Microsoft.GeneratedCode”与 XML 序列化有关。
rxjs ×3
angular ×2
observable ×2
unsubscribe ×2
.net ×1
c# ×1
javascript ×1
rxjs6 ×1
typescript ×1