Skip to content

Instantly share code, notes, and snippets.

@christo8989
Last active February 9, 2018 22:43
Show Gist options
  • Save christo8989/7055642ad054720cc50cbe1aa17bd339 to your computer and use it in GitHub Desktop.
Save christo8989/7055642ad054720cc50cbe1aa17bd339 to your computer and use it in GitHub Desktop.
One way to pass objects around in an angular2 app using RxJS.
import { Injectable } from '@angular/core';
import {
Subject,
BehaviorSubject,
Subscription } from 'rxjs';
@Injectable()
export class GlobalService {
private subjects: object = {};
subscribe<T>(key:string, fn: (value: T) => void, unsubscribe: Subject<any>): Subscription {
this.putSubject<T>(key);
return this.subjects[key]
.takeUntil(unsubscribe)
.subscribe({ next: fn });
}
emit<T>(key: string, value: T): void {
this.putSubject<T>(key);
this.subjects[key]
.next(value);
}
private putSubject<T>(key: string): void {
if (!this.subjects[key]) {
this.subjects[key] = new BehaviorSubject<T>(null);
}
}
}
import {
Component,
OnInit,
OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { GlobalService } from './global.service.ts';
@Component({
selector: 'app-recieve',
templateUrl: './recieve.component.html',
styleUrls: ['./recieve.component.scss']
})
export class ConfigComponent implements OnInit, OnDestroy {
private unsubscribe = new Subject()
public objRecieved: object = null
constructor(private globalService: GlobalService) { }
ngOnInit() {
this.globalService
.subscribe(
"object",
data => this.objRecieved = data,
this.unsubscribe
)
}
ngOnDestroy() {
this.unsubscribe.next()
this.unsubscribe.complete()
}
}
import { Component } from '@angular/core';
import { GlobalService } from './global.service.ts';
@Component({
selector: 'app-send',
templateUrl: './send.component.html',
styleUrls: ['./send.component.scss']
})
export class ConfigComponent {
public objSend: object = {};
constructor(private globalService: GlobalService) { }
onevent(): void {
this.globalService
.emit("object", this.objSend);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment