Reputation: 81
I have an angular 7 app which has multiple route components: questions, answers. These components are not related as in they appear separately under different routes. I can navigate to both using their route paths so I know that's working.
I have set up a data service to share a user (just a name at this stage) across the entire app.
data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService {
private user = new BehaviorSubject<string>('John');
cast = this.user.asObservable();
constructor() { }
editUser(newUser: string) {
this.user.next(newUser);
}
}
Now in each component I have imported and subscribed to this service:
this.data.cast.subscribe(user => this.user = user);
Now in the questions component (questions.component.ts) I have a method that changes the user string value:
editedTheUser() {
this.data.editUser(this.editUser);
}
and in each of the components HTML I have {{ user }}
Now when I trigger that method with a button click and a form value from questions.component.ts the value is updated but only in the questions HTML.
<input type="text" [(ngModel)]="editUser">
<button (click)="editedTheUser()">Change</button>
The idea is to have both routes open in a browser (could be multiple browsers ie. Chrome and Firefox) but still on the same network and have the {{ user }} value updated automatically in both.
The end result is essentially to have all the questions on a tablet and display the answers on a screen. I would prefer not to use sockets if possible as this will only be running in local environments.
Thanks
Upvotes: 0
Views: 180
Reputation: 386
Observables don't work like that.
What you save in the BehaviourSubject, is only available in that instance of your application. Every new page of your app is a new instance.
To do what you want you have to save the data to a Database and you can use websockets to update data in all clients in realtime.
This way you send your data to backend and backend save it and send the update to all active clients on the websocket.
You may use feathersjs or other framework. It's very easy to get started with it if you want to. You may use Firestore, too, wich is easy and free (for something as small as what you're trying.
Upvotes: 1
Reputation: 21658
The service is only the same instance of the service in the Angular app, it is not possible to make it the same instance across different browsers. You will need a server where the editing browser pushes the update to the server and then all other browser will need the update pushed from the server. Sockets would indeed be the right solution for this use case.
Upvotes: 0