Reputation: 583
I'm using a service to communicate between two components. The idea is that when I click 'add to clipboard' on component A, this gets added to sessionStorage. Component B should then retrieve it and update the view.
I've managed to get most of it working so that my items appear in Component B and persist - but only after the page is reset. How can I have Component B refresh each time something is added.
method in component A (sender)
addToClipboard() {
let item: Item = {id : this.itemId, collection : this.collectionName, database : this.dbName, name: itemTitle };
this.clipboardService.addItemToClipboard(item);
}
Service
@Injectable({
providedIn: 'root'
})
export class ClipboardService {
// items$: Observable<Item []>;
// private itemSubject = new Subject<Item []>();
constructor() {
// this.items$ = this.itemSubject.asObservable();
}
addItemToClipboard(item: Item) {
console.log(item);
// this.itemSubject.next(item);
if (sessionStorage.getItem('clipItems') !== null) {
console.log(sessionStorage.length);
const storedItems: Item [] = JSON.parse(sessionStorage.getItem('clipItems'));
storedItems.push(item);
sessionStorage.setItem('clipItems', JSON.stringify(storedItems));
} else {
const items: Item [] = [];
items.push(item);
sessionStorage.setItem('clipItems', JSON.stringify(items));
}
}
getItemsFromClipBoard(): Item [] {
const storedItems: Item [] = JSON.parse(sessionStorage.getItem('clipItems'));
return storedItems;
}
}
component B (reciever)
import { Component, OnInit, OnChanges, ChangeDetectionStrategy } from '@angular/core';
import { Item } from 'src/app/models/item';
import { ClipboardService } from '../clipboard.service';
@Component({
selector: 'app-clipboard',
templateUrl: './clipboard.component.html',
styleUrls: ['./clipboard.component.css'],
})
export class ClipboardComponent implements OnInit {
items: Item [] = [];
constructor(private clipboardService: ClipboardService) {
}
ngOnInit() {
this.items = this.clipboardService.getItemsFromClipBoard();
}
}
Ideally, every time the 'items' list refreshes I'd like to update the component (I've had to use session in the service because the items need to persist until the user logs out).
Upvotes: 0
Views: 740
Reputation: 1944
Store in service variable instead of session and make available as BehaviourSubject so can be subscribed to from any component.
This will persist and you could just have a function to clear the service variable on log out if needed. e.g:
Service:
itemsSubject = new BehaviorSubject<Item[]>(this.getItems());
addItem(item)
{
this.items.push(item);
}
getItems()
{
return this.items;
}
Component:
export class MyComponent
items: Item[];
//constructor
this.clipboardService.itemsSubject.subscribe(res =>
{
this.items= res;
});
Some auth service:
LogOut()
{
//clear session then:
this.clipboardService.items = [];
}
Upvotes: 1