这是我的服务代码,让服务名称为setGetContext
_params: Subject<any> = new Subject<any>();
getParameters(): Observable<SearchContext> {
return this._params.asObservable();
}
setParameters(search: SearchContext) {
this._params.next("Test");
}
在其他组件中,我试图获取params的值。
this.setGetContext.getParameters().subscribe((data) => {
console.log(data);
})
这里我没有获取数据,甚至没有触发代码。
答案 0 :(得分:4)
服务:
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'
答案 1 :(得分:0)
您可以执行以下操作:
您的服务
: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)});