How to get data from asObservable()

依然范特西╮ 提交于 2019-12-11 09:00:08

问题


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

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.


回答1:


The service:

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

The component:

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

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




回答2:


You can do something like this:

Your Service:

import { Observable } from "rxjs/Observable";
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { distinctUntilChanged, map } from 'rxjs/operators';

private _paramSubject = new BehaviorSubject<any>({} as any);
public _params = this._paramSubject.asObservable().pipe(distinctUntilChanged());

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

In the component:

setParameters(<YOUR OBJECT>)
service._params.subscribe(data => {console.log(data)});


来源:https://stackoverflow.com/questions/51380223/how-to-get-data-from-asobservable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!