In my Angular application I have an API which returns the settings of the footer and the header of the web-site. However I want to call that API only once and use the data for both the header and the footer. There's no direct parent of the header and footer components so I can't just call it from the parent component and pass the data to the child components. As I understand, the correct way of doing this is a service. I've tried to do it as it was described here but this doesn't seem to work. So, my idea is that I need to have a dedicated place which will call the HTTP API, get the data and then the other components can just use that service (inject it) to get the data, all in one place.
Any clues how this can be implemented or what's wrong with the implementation in the topic referenced?
The code which doesn't work looks like this:
import { Observable } from 'rxjs/Observable';
@Injectable()
export class PersonService {
// The person subject
personStream: ReplaySubject<Person> = new ReplaySubject();
// The person observable
person$(): Observable<Person> {
return this.personStream.asObservable();
}
// Get person from DB and add to stream
getDataFromDB() {
this.http.get(url).subscribe(response => {
this.personStream.next(response.person);
});
}
}
@Component({...})
export class MyComponent implements OnInit {
person: Person;
constructor(private personService: PersonService) {}
ngOnInit() {
// Subscribe to person observable. Any time person data changes, this will be called.
this.personService.person$().subscribe(person => this.person = person);
// If you return the `this.http.get(url)` from `getDataFromDB`, you can just do this instead...
this.personService.getDataFromDB().subscribe(person => this.person = person);
}
}
Thanks!