javascript - Timing issue: How can I get the correct value of a variable from angular2 service -
in angular2 service raise value of variable inside replace function.
i able access value component, starting value.
so -> 0. able gat value if change in constructor of service, not need.
here service.ts:
export class myservice { colletion: object = { foo: [], bar: [], somethig: [] } counter: = 0; constructor() { getsomedata(); } getsomedata() { //do stuff data server, call: cleanstrings(); } cleanstrings() { (var = 0; < result.length; i++) { this.colletion[key][i] = key + " " + result[i].expression .replace(/string/g, match => { //here raise value this.counter++; return 'field-' + this.counter + '" />'; }); } } }
so guess run timing issue.
here how try value of 'counter' - app.component.ts:
import { component, viewchild, querylist, viewchildren } '@angular/core'; import { myservice } './services/my.service'; @component({ selector: 'app-root', templateurl: './app.component.html', styleurls: ['./app.component.css'], providers: [myservice] }) export class appcomponent { collection: object = {}; counter: any; constructor(private _myservice: myservice) { this.collection = _myservice.colletion; this.counter = _myservice.counter; console.log(this.counter); //says -> 0 }
what have change, correct value after this.counter++; has reached maximum value?
it job rxjs :
update service :
export class myservice { counter: number = 0; ... countersubject: behaviorsubject<number> = new behaviorsubject(this.counter); subscribecounter = (s:any) => { this.countersubject.asobservable().subscribe(s); //subscription next counter values this.countersubject.next(this.countersubject.getvalue()); //get current value @ subscription } ... getsomedata() { //do stuff data server, call: cleanstrings(); countersubject.next(this.counter); } ... }
subscribe in component :
export class appcomponent implements oninit { collection: object = {}; counter: number; constructor(private _myservice: myservice) { } ngoninit() { _myservice.subscribecounter((c) => { this.counter = c; console.log(this.counter); //incremented }); } ... }
Comments
Post a Comment