angular-destroyref
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAngular DestroyRef
Angular DestroyRef
Version: Angular 16+ (2025)
Tags: DestroyRef, Cleanup, takeUntilDestroyed
References: DestroyRef
版本: Angular 16+ (2025)
标签: DestroyRef, Cleanup, takeUntilDestroyed
参考资料: DestroyRef
Best Practices
最佳实践
- Use takeUntilDestroyed
ts
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({})
export class MyComponent {
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.data$.pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe();
}
}- Use in service
ts
@Injectable({ providedIn: 'root' })
export class DataService {
private destroyRef = inject(DestroyRef);
getData() {
return this.http.get('/api/data').pipe(
takeUntilDestroyed(this.destroyRef)
);
}
}- 使用takeUntilDestroyed
ts
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({})
export class MyComponent {
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.data$.pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe();
}
}- 在服务中使用
ts
@Injectable({ providedIn: 'root' })
export class DataService {
private destroyRef = inject(DestroyRef);
getData() {
return this.http.get('/api/data').pipe(
takeUntilDestroyed(this.destroyRef)
);
}
}