需要注意的是,如果在模板中使用可观察对象,需要使用管道(pipe)来更新值。具体来说,可以使用AsyncPipe,这将自动订阅并取消订阅可观察对象,并更新视图。例如:
在组件中:
import { Component } from '@angular/core'; import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
template:
})
export class AppComponent {
public title$: Observable{{ title$ | async }}
constructor() { this.title$ = Observable.of('Hello World'); } }
在模板中:
注意:在使用可观察对象时,请确保在组件销毁时取消订阅。一种常见的方法是在实现OnDestroy接口的ngOnDestroy方法中完成。例如:
import { Component, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-root',
template:
})
export class AppComponent implements OnDestroy {
public title$: Observable{{ title$ | async }}
constructor() { this.title$ = Observable.of('Hello World'); this.subscription = this.title$.subscribe(); }
ngOnDestroy() { this.subscription.unsubscribe(); } }
这将确保在组件销毁时取消订阅,并避免潜在的内存泄漏问题。