如何从 asObservable() 获取数据
How to get data from asObservable()
这是我的服务代码,让服务名称为setGetContext
_params: Subject<any> = new Subject<any>();
getParameters(): Observable<SearchContext> {
return this._params.asObservable();
}
setParameters(search: SearchContext) {
this._params.next("Test");
}
在另一个组件中,我试图获取参数的值。
this.setGetContext.getParameters().subscribe((data) => {
console.log(data);
})
这里我没有获取数据,甚至没有触发代码。
服务:
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'
你可以这样做:
您的服务:
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");
}
组件中:
setParameters(<YOUR OBJECT>)
service._params.subscribe(data => {console.log(data)});
这是我的服务代码,让服务名称为setGetContext
_params: Subject<any> = new Subject<any>();
getParameters(): Observable<SearchContext> {
return this._params.asObservable();
}
setParameters(search: SearchContext) {
this._params.next("Test");
}
在另一个组件中,我试图获取参数的值。
this.setGetContext.getParameters().subscribe((data) => {
console.log(data);
})
这里我没有获取数据,甚至没有触发代码。
服务:
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'
你可以这样做:
您的服务:
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");
}
组件中:
setParameters(<YOUR OBJECT>)
service._params.subscribe(data => {console.log(data)});