I have 2 components which are unrelated, navbar
and edit-page
In the navbar
component I get a list of page titles from a collection, and I use the edit-page
component to edit a page title, but since I can always see all the page titles from the navbar
component, I want it to be updated as soon as I edit a page title.
How to achieve this without @input
and @output
? As far as I understand I should creating some kind of a shared service but I am not sure how to go about it exactly?
pages.service.ts
import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
@Injectable()
export class PagesService {
constructor(private http: Http) { }
getPages() {
return this.http.get('http://localhost:3000/pages')
.map(res => res.json());
}
getEditPage(id) {
return this.http.get('http://localhost:3000/pages/edit-page/' + id)
.map(res => res.json());
}
postEditPage(value) {
return this.http.post('http://localhost:3000/pages/edit-page/' + value.id, value)
.map(res => res.json());
}
}
navbar component
pages: any[];
ngOnInit() {
this.pagesService.getPages().subscribe(pages => {
this.pages = pages;
});
}
edit-page component
editPage({ value, valid }) {
if (valid) {
this.pagesService.postEditPage(value).subscribe(res => {
if (res == "ok") {
this.successMsg = true;
}
});
} else {
console.log('Form is not valid');
}
}
So after the editPage
method is executed in the edit-page
component I would like the pages
property in the navbar
component to be updated automatically.