How to unregister push from another page instead of push initialised push page


#1

Hello,

I have registered push at login page. But now i am not able to unregister push from logout page. Please help


#2

@aditya_1027 I think its better to use observables in your case, because that approach is not appropriate (you have to know what one page did in the other, it’s error prone and so on).

You can do something like the following, adapting to your code:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';

@Injectable()
export class UserService {
	private login$ = new Subject<void>();
	private logout$ = new Subject<void>();

	public login() {
		// login stuff
		// after successful login (inside an async call, probably):
		this.login$.next();
	}

	public logout() {
		// logout stuff
		// after successful logout (inside an async call, probably):
		this.logout$.next();
	}

	public getLoginNotifier(): Observable<void> {
		return this.login$.asObservable();
	}

	public getLogoutNotifier(): Observable<void> {
		return this.logout$.asObservable();
	}
}

And to register the push notifications:

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs/Rx';

@Injectable()
export class PushService {
	private registered: boolean = false;

	constructor(private userService: UserService) { }

	public init() {
		this.userService.getLogoutNotifier().subscribe(() => {
			if (this.registered) {
				// unregister here
				this.registered = false;
			}	
		});

		this.userService.getLoginNotifier().subscribe(() => {
			if (!this.registered) {
				// register here
				this.registered = true;
			}	
		});
	}
}

You can then inject the PushService inside the AppComponent and call init() in the ngOnInit() of the component.

You may prefer to have only one Subject<boolean> passing true in login and false in logout.

You also may prefer to listen the register and unregister notifications in another service or component, so the PushService will handle only the push registration an unregistration, without worrying with when the push must be registered and unregistered.