There are a bunch of ways to approach this, and here’s one.
I prefer to program backwards from consumers to producers, because I find that when I write producers first, I put all sorts of stupid stuff in them that I never use and leave out super-important stuff that I have to add later.
So what does our consumer want? As I understand it, it wants to give us a phone number and get a message back:
class MessageService {
messagesForTelno(telno: string): Observable<string> {
// TODO
}
}
Now, given that we have the JSON object you posted, and for the sake of simplicity we’ll just hardcode it into our service:
interface Message {
phone: string;
message: string;
}
private upstream: Message[] = [
{ phone: ‘11113333’, message: ‘hello’ },
{ phone: ‘22223333’, message: ‘bye’ },
{ phone: ‘33334444’, message: ‘good-bye’ },
];
That’s not very convenient for messagesForTelno, because it would like to do something like this:
messagesForTelno(telno: string): Observable<string> {
return of(this.messages[telno]);
}
So now we’ve reduced our problem to how to get what we have (upstream) into what we want (messages):
private messages: { [telno: string]: string };
constructor() {
this.messages = {};
this.upstream.forEach(msg => {
this.messages[msg.phone] = msg.message;
});
}
Now you can inject MessageService into each of your pages and call messagesForTelno() with a phone number, and you will receive an Observable<string> of messages intended for that phone number. Currently as written, that’s only a single message, but this design would extend naturally to providing a stream of messages instead.