且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 5 订阅和取消订阅 Observable

更新时间:2023-08-23 14:56:28

Behavior Subject, Subscribe &取消订阅 Observables

行为主体在多个组件***享数据时非常有用.您可以根据需要多次订阅它们.您也可以使用取消订阅方法取消订阅.

Behavior Subject, Subscribe & Unsubscribe Observables

Behavior subjects are very useful while sharing data in multiple components. You can subscribe them as many times as you want. Also you can unsubscribe it using unsubscribe method.

让我们使用上述服务并订阅该服务以获取数据:

Let's take the above service and subscribe that service to get data:

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() 方法更新行为主体源值的方法.

Here, I have declared a behavior subject with initial value empty string. Just remember that you need to give a default value to your behavior subject whether it a blank string or any number. After that, I have initialized an observable data using asObservable() method. And finally, I have created a method which updates the behavior subject source value using next() method.

现在我将在我们的组件中使用这个服务来从我们的行为主体中获取数据.

Now I will use this Service in our component to get data from our behavior subject.

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 注入到我们的组件中,并创建了该 DataService dataSvc 的实例.我已经使用 dataSvc 来调用我们的数据 observable 并订阅该数据 observable 以从我们的行为主体中获取数据.因此,我将通过以下代码在浏览器控制台中获得的输出是:

Here I have injected our DataService to our component and I have created an instance of that DataService dataSvc. I have used dataSvc to call our data observable and subscribe that data observable to get data from our behavior subject. So the output which I will get in the browser console by the following code is:

Data: 

所以我得到这个是空的,因为我使用了一个空字符串作为我的行为主题的默认值.

So I am getting this empty because I have used an empty string as the default value for my behavior subject.

现在要更新行为主题的值,我必须使用 dataSvc 服务的更新方法,它将空字符串的 BehaviorSubject 值更新为新值.

Now to update the value of behavior subject, I have to use update method of dataSvc service which will update the value of BehaviorSubject for the empty string to the new value.

//Insert this before subscribing the data observable
this.dataSvc.update('abc');

//Output in the console.
Data: abc

现在该值已从空字符串更新为 abc.这将反映在订阅此 BehaviorSubject 的每个组件中.

Now the value has been updated from empty string to abc. And this will reflect in each and every component where are subscribing this BehaviorSubject.

如果我想取消订阅该订阅怎么办.所以我们必须将订阅初始化为

So what if I want to unsubscribe this subscription. So we have to initialize subscription as

subscription: ISubscription;

然后每当我们想要取消订阅时,我们都会像这样调用 ISubscription 的取消订阅方法

and then whenever we want to unsubscribe we will call unsubscribe method of ISubscription like this

this.subscription.unsubscribe();

因此特定组件的完整代码将如下所示:

So the complete code for a particular component will be like this:

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();
  }
}