Angular 5 订阅和取消订阅 Observable [英] Angular 5 subscribe and unsubscribe Observable

查看:115
本文介绍了Angular 5 订阅和取消订阅 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从两个订阅中获取数据,但我总是得到第一个的数据.

I have to get datas from two subscribe but I get always data of the first one.

我有一个数据共享服务:

I have a data shared service :

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';


@Injectable()
export class DataService {

    private source = new BehaviorSubject<any>('');
    data = this.source.asObservable();

    constructor() { }

    update(values: any) {
        this.source.next(values);
    }
}

在离开搜索组件之前,我调用了更新方法.
现在,我在结果组件上.我得到这样的共享数据:

Before leaving search component, I call update method.
Now, I'm on the results component. I get shared data like that :

constructor(private dataSvc: DataService,
        private router: Router,
        private rideStore: RideStore) { }

    ngOnInit() {
        this.getData();
    }

    getData() {
        this.subscription = this.dataSvc.data.take(1).subscribe(
            data => this.data = data ? data : undefined,
            err => console.log(err),
            () => this._isValid()
        );
    } 

我的问题是:我需要共享数据来订阅另一个 observable.首先,我构造了一个对象ride,然后调用了搜索方法

My question is : I need shared data to subscribe to another observable. First, I construct an object ride and after i call the search method

    search() {
    this.rideStore.searchRides(this.ride).subscribe(
        rides => {
            // this.dataSvc.update(rides);
            this.rides = rides;
            console.log('results', this.ride);
        },
        err => console.log('err', err)
    );
}

问题是我总是从数据服务而不是从 api 调用中获取数据.api 有效,因为我拦截了存储中的结果,但不在组件中.那么我如何才能停止订阅第一个 observable 并订阅第二个?

The problem is I always get data from data service and not from the api call. The api works cause I intercept results in store but not in the component. So How I can stop subscribing first observable and subscribe of the second ?

推荐答案

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

这篇关于Angular 5 订阅和取消订阅 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆