I have a straightforward setup, consisting of various elements and a singular service [StackBlitz]:
https://i.sstatic.net/y6AFT.png
Service
@Injectable()
export class Service {
constructor(private http: HttpClient) {}
saveItem(item: IItem): Observable<IItem> {
return this.http
.post<IItem>('/api/item', item)
.pipe(map(parseDates));
}
retrieveItems(): Observable<IItem[]> {
return this.http
.get<IItem[]>('/api/item')
.pipe(map(parseDates));
}
}
Element0
@Component({
selector: 'app-element0',
template: `<app-element1></app-element1>
<app-element2></app-element2>`,
styleUrls: []
})
export class Element0 {}
Element1
@Component({
selector: 'app-element1-create',
template: `<button (click)="submit()">Submit</button>`,
styleUrls: []
})
export class Element1 {
constructor(private service: Service) { }
submit() {
this.service.saveItem({name: 'example'})
.subscribe(console.info, console.error)
}
}
Element2
@Component({
selector: 'app-element2-list',
template: `<pre>{{ items | json }}</pre>`,
styleUrls: []
})
export class Element2 implements OnInit {
items: IItem[];
constructor(private service: Service) { }
ngOnInit() {
this.service.retrieveItems()
.subscribe(items => this.items = items,
console.error)
}
}
Is there a way for Element1
to update Element2
using the Service
?