Rxjs - block subsequent requests while waiting for method to execute - javascript

I have a class, UserPermissionsService, that makes a server request when it's initially accessed. Once the request completes, subsequent calls use the data that's stored in a BehaviorSubject to complete their operations. However, if multiple happen simultaneously, the init method won't have completed and multiple server requests will occur.
How can I refactor the below class to force subsequent calls to wait for the initial init request to complete prior to executing?
#Injectable({
providedIn: 'root'
})
export class UserPermissionsService implements OnDestroy{
private _permissions = new BehaviorSubject<AppliedPermissions>(null);
public permissionSnapshot: AppliedPermissions;
public permissions: Observable<AppliedPermissions> = this._permissions.asObservable();
constructor(private _userService: UserService) {
}
init(): Observable<AppliedPermissions> {
return this._userService.getPermissions()
.pipe(tap(p => {
this._permissions.next(p)
this.permissionSnapshot = p;
}));
}
hasPermission(permission: string): Observable<boolean> {
return this._permissions.pipe(
switchMap(value => value ? of(value) : this.init()),
map(response => {
const perm = response.permissions
.find(el => el.permissionName === permission);
if (!perm)
return false;
return perm.allow;
}),
catchError(_ => of(false))
);
}
inRole(role: string): Observable<boolean> {
return this._permissions.pipe(
switchMap(value => value ? of(value) : this.init()),
map(response => {
return !!response.roles.find(el => el === role);
}),
catchError(_ => of(false))
);
}
ngOnDestroy(): void {
this._permissions?.complete();
}
}

did you consider OnInit()
export class App implements OnInit {
constructor() {
// Called first time before the ngOnInit()
}
ngOnInit() {
// Called after the constructor and called after the first ngOnChanges()
}
}
Now to your answer - try flatmap to preserve/control the sequence, this ensures that the order of execution is retained. for e.g. see here
first
.flatMap(() => second)
.flatMap(() => third)
.subscribe(()=> console.log('finished'));
Another option
// use this wrapper
function WaitForComplete<T>(signal: Observable<any>) {
return (sourceInit: Observable<T>) => signal.pipe(
first(), switchMap(_ => sourceInit),
);
}
// force the waiting to complete, by deferring the subscribe on the first source
// till the signal observable completes/emits (many versions of this out there)
var YourSecond =
anotherObservable.pipe(WaitForComplete(YourFirstObservableFunction), take(1));
Update: services can implement ngOnInit()

I would personally replace:
switchMap(value => value ? of(value) : this.init()),
wirth
filter(value=>!!value)
Assuming that you want to do the request only in initial init and just wait for it to finish

Related

A specific post call is called twice?

I have an app, and there is many place where we execute post request call.
But, in one place in the application, a call is executed twice :
in my service I have
PostNewStory(params:API_TYPE.post_new_item_history_call){
let observable$ = this._http.Get(UtilsService.apiServer + '/post_new_item_history', params)
let subscription = observable$.subscribe((data:any) =>{
//do stuff
subscription.unsubscribe();
});
return observable$;
}
In My component I have
PostComment(){
const params = {
//params
};
this._itemDetailsService.PostNewStory(params).subscribe((data:post_new_item_history_response) => {
this.ResetCommentArea();
});
}
I have an HttpService like following
public Post<T>(url: string, payload: any): Observable<T>;
public Post<T>(url, payload): Observable<T> {
return this.http.post<T>(url, payload, httpHeaders)
.pipe(
retry(MAX_RETRY)
)
}
This works perfectly everywhere, I checked, every function is called Once, and only once. If I put a log here =>
public Post<T>(url: string, payload: any): Observable<T>;
public Post<T>(url, payload): Observable<T> {
console.log("MyLog")
return this.http.post<T>(url, payload, httpHeaders)
.pipe(
retry(MAX_RETRY)
)
}
I do have only one log. But the call is done twice ?
You are subscribing to the http request observable twice, once in PostNewStory, then you return the observable, and subscribe to it again in PostComment.
Try something like this :
PostNewStory(params:API_TYPE.post_new_item_history_call){
let observable$ = this._http.Get(UtilsService.apiServer + '/post_new_item_history', params)
return observable$.pipe(
map((data: any) => {
// do stuff
return dataNeededInPostCommentMethod;
}),
);
}

Return a Observable from a Subscription with RxJS

I currently have a service that do a HTTP request to an API to fetch data. There are some logic that I want to do to the observable from within the service, but I still want to also subscribe to the Observable in my Component so that I can return any errors to the Component and to the user.
Currently I do:
// service.ts
getData(): Observable<any> {
return this.http.get(url).pipe(catchError(this.handleError)
}
// component.ts
ngOnInit() {
this.service.getData().subscribe(res => {
// Do my logic that belong to the service.ts
// ...
// Do my logic that belongs in the component.ts
// ...
}, err => this.errors = err)
}
What I would like to do is to refactor this so that I handle the logic related to the subscription and the service.ts within the getData() method, and then return an Observable with the HTTP response and any errors to the Component so that I can continue doing things there.
What's the pattern to do this?
I feel like multiple of the patterns and solutions posted is "ugly" or does not follow the Observable pattern (Like doing callbacks).
The cleanest, most "RxJS"-like solution I came up with was to wrap the service method's return value in a second Observable.
So the following:
// service.ts
getData(): Observable<any> {
return new Observable(subscriber => {
this.http.get(url)
.pipe(catchError(this.handleError)
.subscribe(res => {
// Do my service.ts logic.
// ...
subscriber.next(res)
subscriber.complete()
}, err => subscriber.error(err))
})
}
// component.ts
ngOnInit() {
this.service.getData().subscribe(res => {
// Do my component logic.
// ...
}, err => this.errors = err)
}
Use map:
// service.ts:
import { catchError, map } from 'rxjs/operators';
getData(): Observable<any> {
return this.http.get(url).pipe(
map(res => {
/* Your processing here */
return res;
}),
catchError(this.handleError)
)
}
Try this way
service.ts
getData(): Observable<any> {
return this.http.get(url).map(res=> <any>(res['_body']));
}
component.ts
this.service.getData().subscribe(response=>{
var res1 = JSON.stringify(response);
var res2 = JSON.parse(res1);
var res3 = JSON.parse(res2);
}); //parse response based on your response type
Option 1
If you subscribe Observable in component then only component will have that subscription and it must be passed back to service.
Option 2
Use this pattern.
service.ts
getData(doer: Function) {
let subscriptions = Observable.of({ data: 'response', isError: false })// request
.catch(error => Observable.of({ data: error, isError: true })) //handle error
.do(data => doer(data))
.subscribe();
this.handleSubscription(subscriptions); //subscription handling in service
}
component.ts
ngOnInit() {
this.getData(response => {
if (response.isError) {
///
} else {
let data = response.data;
// Process
}
})
}
Be careful: All the answers are for <= Angular 4. In Angular 5, you don't need a map() anymore, so just leave that out. just return this.http.get() as it returns an Observable, where you can subscribe on.
Furthermore, be aware you have to import HttpClient instead of Http.
You can directly use "map" and "catch" function on Observable returned by http.get method.
import { catchError, map } from 'rxjs/operators';
getData(): Observable<any> {
return this.http.get(url)
.map(res => {
/* Your processing here */
return res;
})
.catch(this.handleError);
}
You can remove this, and use map. In subscribe error, you can get error event.
If you use HttpClient, just use get!

Fetch data once with Observables in Angular 2

I have a service, what is used several times from a lot of my Angular 2 components. It fetches customer data from a Web API and returns an Observable:
getCustomers() {
return this.http
.get(this.baseURI + this.url)
.map((r: Response) => {
let a = r.json() as Customer[];
return a;
});
}
I inject this service in my root component, and in every component that wants to access the customers I just subscribe to that Observable:
this.customerService.getCustomers().subscribe(v => this.items = v);
However, every component who subscribes to my Observable causes another execution of the HTTP-request. But to fetch the data only once is enough.
If I try share(), it does not solve my problem:
getCustomers() {
return this.http
.get(this.baseURI + this.url)
.map((r: Response) => {
let a = r.json() as Customer[];
return a;
}).share();
}
Still the same issue. Any proposals which operators I have to use to only fetch data once?
1) You can simply save downloaded data in your service:
export class CustomersService {
protected _customers: Array<Customer>;
constructor(public http: Http) {}
public getCustomers(): Observable<Array<Customer>> {
return new Observable(observer => {
if (this._customers) {
observer.next(this._customers);
return observer.complete();
}
this.http
.get(this.baseURI + this.url)
.map((r: Response) => (r.json() as Array<Customer>))
.subscribe((customers: Array<Customer>) => {
this._customers = customers;
observer.next(this.customers);
observer.complete();
});
});
}
}
2) Shorter approach taking refresh parameter:
export class CustomersService {
protected _customers: Array<Customer>;
constructor(public http: Http) {}
public getCustomers(refresh?: boolean): Observable<Array<Customer>> {
if (!refresh && this._customers) {
return Observable.of(this._customers);
}
return this.http
.get(this.baseURI + this.url)
.map((c: Response) => (c.json() as Array<Customer>))
.do((customers: Array<Customer>) => {
this._customers = customers;
});
});
}
}
3) Taking advantage of ReplaySubject:
export class CustomersService {
protected _customers$: ReplaySubject<Array<Customer>> = new ReplaySubject(1);
protected _customersInitialized: boolean;
constructor(public http: Http) {}
public getCustomers(refresh?: boolean): Observable<Array<Customer>> {
if (refresh || !this._customersInitialized) {
this._customersInitialized = true;
this.http
.get(this.baseURI + this.url)
.map((c: Response) => (c.json() as Array<Customer>))
.subscribe((customers: Array<Customer>) => {
this._customers$.next(customers);
});
}
return this._customers$.asObservable().skip(+refresh).distinctUntilChanged();
}
}
And then:
this.customersService.getCustomers()
.subscribe(customers => this.customers = customers);
You can also expose the always up-to-date customers field from SomeService for read only purposes (like displaying in the templates) this way:
public get customers(): ReadonlyArray<Customer> {
return this._customers;
}
I would create a parent container, fetch the data once, and pass it to child components using #Input.
Parent:
#Component({
selector: 'BarFooHttpCaller',
template: ´<child *ngIf="data.length > 0" [data]></child>´
})
class BarFooHttpCaller {
private data: any;
constructor(private foobar:Foobar) {
this.data = {};
}
ngOnInit() {
this.foobar.getCustomers().subscribe(() => {
console.log('httpdone')
});
this.foobar.dataStream.subscribe((data) => {
console.log('new data', data);
this.data = data;
})
}
}
Child:
import { Component, Input } from '#angular/core';
#Component({
selector: 'child',
template: ´<div>{{data}}</div>´
})
export class Child {
#Input() data: any;
}
If you want multiple children to subscribe to the same observable, but only execute the observable once you can do the following.
Note that this does adhere to the design of observables since we are executing the observable in the service layer (Observable.fromPromis(stream.toPromise()) when execution should be done from the component subscribing. View https://www.bennadel.com/blog/3184-creating-leaky-abstractions-with-rxjs-in-angular-2-1-1.htm for more.
//declare observable to listen to
private dataObservable: Observable<any>;
getData(slug: string): Observable<any> {
//If observable does not exist/is not running create a new one
if (!this.dataObservable) {
let stream = this.http.get(slug + "/api/Endpoint")
.map(this.extractData)
.finally(() => {
//Clear the observable now that it has been listened to
this.staffDataObservable = null;
});
//Executes the http request immediately
this.dataObservable = Observable.fromPromise(stream.toPromise());
}
return this.staffDataObservable;
}
the share operator give the possibility to use the same stream's result with multiple observers. It could be good but you generate a new observable stream each time you call getCustomers(), there is no point to call share() since you didn't subscribe multiple times to this stream.
If you wanna share the data with multiple observers but make only one http call you simply have to create a second stream, feed by the http one, containing the data. After that, all your components could subscribe to it.
The code could be something like that
#Injectable()
class FooBar {
public dataStream:Subject<any> = new Subject();
constructor(private http:Http) {}
public getCustomers() {
return this.http
.get(this.baseURI + this.url)
.map((response:Response) => response.json())
.map((data) => {
this.dataStream.next(data);
return data;
})
}
}
#Component({})
class BarFooHttpCaller {
constructor(private foobar:Foobar) {}
ngOnInit() {
this.foobar.getCustomers().subscribe(() => { console.log('http done') });
this.foobar.dataStream.subscribe((data) => {
console.log('new data', data);
})
}
}
#Component({})
class OtherBarFoo {
constructor(private foobar:Foobar) {}
ngOnInit() {
this.foobar.dataStream.subscribe((data) => {
console.log('new data', data);
})
}
}
No need for custom implementations. A pipe will do the trick:
getCustomers$(): Observable<Customer> {
return this.http
.get<Customer>(this.baseURI + this.url)
.pipe(shareReplay(1));
}
Couple of things I did here:
Add shareReplay(1) pipe, to make sure the request is only done once (only thing needed to answer the question)
Remove map and made the get call typed
Postfix method name with $ to indicate an Observable is returned

How to use an observable in angular 2 guards' canActivate()

I have created an authentication guard for my angular2 rc5 application.
I am also using a redux store. In that store I keep the user's authentication state.
I read that the guard can return an observable or promise (https://angular.io/docs/ts/latest/guide/router.html#!#guards)
I can't seem to find a way for the guard to wait until the store/observable is updated and only after that update return the guard because the default value of the store will always be false.
First try:
#Injectable()
export class AuthGuard implements CanActivate {
#select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
// updated after a while ->
this.authenticated$.subscribe((auth) => {
// will only reach here after the first update of the store
if (auth) { resolve(true); }
// it will always reject because the default value
// is always false and it takes time to update the store
reject(false);
});
});
}
}
Second try:
#Injectable()
export class AuthGuard implements CanActivate {
#select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
// tried to convert it for single read since canActivate is called every time. So I actually don't want to subscribe here.
let auth = this.authenticated$.toPromise();
auth.then((authenticated) => {
if (authenticated) { resolve(true); }
reject(false);
});
auth.catch((err) => {
console.log(err);
});
}
}
When you subscribe to an observable, you can provide a callback function; in the example below, I call it CompleteGet. CompleteGet() will only be invoked on a successful get that returns data and not an error. You place whatever follow on logic you need in the callback function.
getCursenByDateTest(){
this.cursenService
.getCursenValueByDateTest("2016-7-30","2016-7-31")
.subscribe(p => {
this.cursens = p;
console.log(p)
console.log(this.cursens.length);
},
error => this.error = error,
() => this.CompleteGet());
}
completeGet() {
// the rest of your logic here - only executes on obtaining result.
}
I believe you can also add a .do() to the observable subscription to accomplish the same thing.
all you need to do is force the observable to update:
canActivate(): Observable<boolean> {
return this.authenticated$.take(1);
}
Edit:
canActivate waits for the source observable to complete, and (most likely, I don't know what happens behind the scenes), the authenticated$ observable emits .next(), not .complete()
From documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-take
.take(1) method takes first value emitted by the source observable and then completes
Edit2:
I just looked at snippet you pasted, and I was right - the store.select() observable never completes, it always emits .next
Subscribe doesn't return an Observable.
However, you can use the map operator like that:
this.authenticated$.map(
authenticated => {
if(authenticated) {
return true;
}
return false;
}
).first() // or .take(1) to complete on the first event emit

How can I return the Http response?

I'm wondering if following thing is possible to do:
I need to return the response from http GET request directly instead of returning Observable<Response> instance.
The example might clarify whole thing a bit:
#Injectable()
export class ExampleService {
constructor( #Inject(Http) protected http: Http) { }
static model: { [uri: string]: any } = {}
public get(uri: string): any {
if (typeof ExampleService.model[uri] === 'undefined') {
ExampleService.model[uri] = this.http.get(uri).map(response => response.json()) // additionally do some magic here, it is Observable<any> instance now
}
return ExampleService.model[uri]
}
}
Summary: according to Günter Zöchbauer answer above solution is not possible, instead of that I need to use something like this:
public get(uri: string): Observable<any> {
return new Observable(observer => {
if (!ExampleService.model[uri]) {
let sub = this.http.get(uri).map(response => response.json()).subscribe(
src => observer.next(ExampleService.model[uri] = src),
err => console.error(err),
() => observer.complete()
)
return () => sub.unsubscribe()
}
observer.next(ExampleService.model[uri])
observer.complete()
})
}
This is not possible because the HTTP request is async and the get() method returns before the call to the server is even made. Instead when the response from the server arrives the callback passed to subscribe(...) is called.
There is no way to go back from async to sync execution.
You can only return the observable for the caller to subscribe to it and do something when the response arrives.

Categories

Resources