angular-reactive

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Angular Reactive Programming

Angular响应式编程

Version: Angular 21 (2025) Tags: Reactive, Observables, RxJS, BehaviorSubject
References: Reactive GuideRxJS
版本: Angular 21 (2025) 标签: Reactive, Observables, RxJS, BehaviorSubject
参考: 响应式指南RxJS

Best Practices

最佳实践

  • Use BehaviorSubject for state
ts
@Injectable({ providedIn: 'root' })
export class StateService {
  private state = new BehaviorSubject<State>(initialState);
  state$ = this.state.asObservable();
  
  updateState(newState: Partial<State>) {
    this.state.next({ ...this.state.value, ...newState });
  }
}
  • Use Observable in services
ts
@Injectable({ providedIn: 'root' })
export class DataService {
  private http = inject(HttpClient);
  
  getData(): Observable<Data[]> {
    return this.http.get<Data[]>('/api/data');
  }
}
  • Use async pipe
ts
@Component({
  template: `
    @if (data$ | async; as data) {
      {{ data.name }}
    }
  `
})
export class MyComponent {
  data$ = this.service.getData();
}
  • Use shareReplay for caching
ts
data$ = this.http.get('/api/data').pipe(
  shareReplay(1)
);
  • Use takeUntil for cleanup
ts
@Component({})
export class MyComponent implements OnDestroy {
  private destroy$ = new Subject<void>();
  
  ngOnInit() {
    this.data$.pipe(takeUntil(this.destroy$)).subscribe();
  }
  
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
  • 使用BehaviorSubject管理状态
ts
@Injectable({ providedIn: 'root' })
export class StateService {
  private state = new BehaviorSubject<State>(initialState);
  state$ = this.state.asObservable();
  
  updateState(newState: Partial<State>) {
    this.state.next({ ...this.state.value, ...newState });
  }
}
  • 在服务中使用Observable
ts
@Injectable({ providedIn: 'root' })
export class DataService {
  private http = inject(HttpClient);
  
  getData(): Observable<Data[]> {
    return this.http.get<Data[]>('/api/data');
  }
}
  • 使用async管道
ts
@Component({
  template: `
    @if (data$ | async; as data) {
      {{ data.name }}
    }
  `
})
export class MyComponent {
  data$ = this.service.getData();
}
  • 使用shareReplay实现缓存
ts
data$ = this.http.get('/api/data').pipe(
  shareReplay(1)
);
  • 使用takeUntil进行资源清理
ts
@Component({})
export class MyComponent implements OnDestroy {
  private destroy$ = new Subject<void>();
  
  ngOnInit() {
    this.data$.pipe(takeUntil(this.destroy$)).subscribe();
  }
  
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}