Here is the complete solution.
1) Angular store as a service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StoreService {
customer: any;
constructor() { }
}
2) Api service to get the data and store it inside the store (a timeout is
used to simulate the async process)
import { Injectable } from '@angular/core';
import { StoreService } from './store.service'
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(
private store: StoreService
) { }
getData() {
setTimeout(()=> {
this.store.customer = {
name: 'Bob',
age: 25
}
}, 1000);
}
}
3) The typescript of your component
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service'
import { StoreService } from '../store.service'
@Component({
selector: 'app-mycomponent',
templateUrl: './mycomponent.component.html',
styleUrls: ['./mycomponent.component.css']
})
export class MycomponentComponent implements OnInit {
customer: any;
constructor(
private api: ApiService,
private store: StoreService
) { }
ngOnInit() {
this.api.getData();
}
}
4) The template of your component
<p>
mycomponent works!
</p>
<ul>
<li>name : {{store.customer?.name}}</li>
<li>Age : {{store.customer?.age}}</li>
</ul>
All the components importing the same store are then related by the two way
data binding. A change of *store.customer.name*, for instance, in one of
these components will be natively propagated to all other components
importing the same store. At any time the store relates the current state
of your app. For instance you can backup it (to the server, to the
IndexedDB, ...) in order to setup a rewind/forward behavior.
Cheers
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/angular/948fc0c9-982e-4fa3-9775-ed298534259f%40googlegroups.com.