如何从asObservable()获取数据 [英] How to get data from asObservable()

查看:404
本文介绍了如何从asObservable()获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的服务代码,让服务名称为setGetContext

this my service code, let the service name be setGetContext

_params: Subject<any> = new Subject<any>();

getParameters(): Observable<SearchContext> {
    return this._params.asObservable();
}

setParameters(search: SearchContext) {
    this._params.next("Test");
}

在其他组件中,我试图获取params的值.

In the other component i'm trying to get the value of params.

this.setGetContext.getParameters().subscribe((data) => {
    console.log(data);
})

这里我没有获取数据,甚至没有触发代码.

Here I'm not getting data and the code is not even triggered.

推荐答案

服务:

public _params: Subject<any> = new Subject<any>();
setParameters(search: SearchContext) {
  this._params.next({action:'test'});
}

组件:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Your service } from 'service_route'

export class YourComponent implements OnInit {
    public subscription: Subscription;

    constructor(private _serv: YourService) {}

    ngOnInit() {
       this.handleSubscriptions();
    }
    public handleSubscriptions() {
      this.subscription = this._serv._params.subscribe(
        action => {
            console.log(action);
        }
      )
    }
}

现在您可以调用服务功能,每次调用该功能时,组件都将console.log'test'

Now you can call your service function and everytime you call it your component will console.log 'test'

这篇关于如何从asObservable()获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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