问题
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