行为主体、订阅和取消订阅 Observables
行为主体在多个组件中共享数据时非常有用。您可以根据需要多次订阅。您也可以使用取消订阅方法取消订阅。
让我们使用上面的服务并订阅该服务来获取数据:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
public source = new BehaviorSubject<any>(' ');
data = this.source.asObservable();
constructor() { }
update(values: any) {
this.source.next(values);
}
}
在这里,我声明了一个初始值为空字符串的行为主体。只要记住你需要给你的行为主体一个默认值无论是空白字符串还是任何数字。之后,我使用初始化了可观察数据asObservable()方法。最后,我创建了一个方法,使用它更新行为主题源值next() method.
现在我将在我们的组件中使用这个服务来从我们的行为主体获取数据。
subscription: any;
constructor( private dataSvc: DataService ) {
this.subscription = this.dataSvc.data.subscribe(
data => console.log('Data:', data),
err => console.log(err),
() => console.log('complete')
);
}
在这里我注入了我们的数据服务到我们的组件,我创建了该 DataService 的一个实例dataSvc。我使用 dataSvc 来调用我们的数据可观察对象并订阅该数据可观察对象以从我们的行为主体获取数据。因此,我将通过以下代码在浏览器控制台中获得的输出是:
Data:
所以我得到了这个空,因为我使用了一个空字符串作为我的行为主题的默认值。
现在要更新行为主体的值,我必须使用 dataSvc 服务的更新方法,该方法会将空字符串的BehaviorSubject 值更新为新值。
//Insert this before subscribing the data observable
this.dataSvc.update('abc');
//Output in the console.
Data: abc
现在该值已从空字符串更新为 abc。这将反映在订阅此BehaviourSubject 的每个组件中。
那么如果我想取消订阅这个订阅怎么办?所以我们必须将订阅初始化为
subscription: ISubscription;
然后每当我们想要取消订阅时,我们都会像这样调用 ISubscription 的取消订阅方法
this.subscription.unsubscribe();
因此,特定组件的完整代码将如下所示:
import { Component } from '@angular/core';
import { DataService } from "./data.service";
import {ISubscription} from "rxjs/Subscription";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
subscription: ISubscription;
constructor( private dataSvc: DataService ) {
this.subscription = this.dataSvc.data.subscribe(
data => console.log('Data:', data),
err => console.log(err),
() => console.log('complete')
);
this.dataSvc.update('abc');
this.subscription.unsubscribe();
}
}