Angular 4 - Call database API only once for 2 components -
gurus, please help.
service - having method getconfig() fetch data database , storing output in behavioursubject observable configarray$
app.component.ts - calls getconfig() first , emits output configarray$
status.component.ts - using resolver route prepopulate data component needs same data/output got app.component.ts getconfig() aip call.
i tried different approaches using setinterval, promise, observable wait appl.component.ts getconfig() method completed pass status.component.ts resolver route, non of working.
i not sure doing correct, can please how address requirement?
thank you.
code:
thank catalyst quick response. here complete code:
config.service.ts
@injectable() export class configservice { private configsarray = new behaviorsubject<config>(undefined); configsarray$ = this.configsarray.asobservable().first(); updateconfigs(configs: config) { this.configsarray.next(configs) } getconfigs() { let initialload: number = 0; let initialloaddone: boolean = false; if (this.fetchconfigs) == 'notfetched') { // if meets if condition working let headers = new headers(); headers.append('content-type','application/json'); this.updatefetchconfigs('fetching'); return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers }).map((response: response) => response.json()); } else { // if not meet if condition not working observable.interval(1) .takewhile(() => !initialloaddone) .subscribe(() => { ++initialload; if (this.getconfigs1(this.fetchconfigs$) == 'fetched' || initialload > 10000) { initialloaddone = true; return this.configsarray$; } }); } } }
config-resolver.service.ts
@injectable() export class configresolver implements resolve<config> { config: config; constructor(private configservice: configservice, private router:router) {} resolve(route: activatedroutesnapshot, state: routerstatesnapshot): observable<config> | promise<config> | config { return this.configservice.getconfigs().map( data => { return data; } ); } }
status.component.ts
export class statuscomponent implements oninit, ondestroy { constructor(private configservice:configservice, private route: activatedroute, private router: router) {} ngoninit() { this.configsubscription = this.route.data.subscribe( (data: data) => { this.test = data['config']; } ); } }
Comments
Post a Comment