简体   繁体   中英

Timing issue: How can I get the correct value of a variable from angular2 service

In an Angular2 Service I raise value of a variable inside a replace function.

I am able to access the value from another component, but I always get the starting value.

So I always get -> 0. I am able to gat another value if I change it in the constructor of my service, but this is not what i need.

Here is my service.ts:

  export class MyService {
    colletion: Object = { foo: [], bar: [], somethig: [] }
      counter: any = 0;

      constructor() {    
          getSomeData();
      }

     getSomeData() {
      //Do stuff to get some data from server, then call:
      cleanStrings();
     }

      cleanStrings() {
        for (var i = 0; i < result.length; i++) {
          this.colletion[key][i] = key + " " + result[i].expression
          .replace(/string/g, match => {

            //HERE I RAISE THE VALUE
            this.counter++; 

            return 'FIELD-' + this.counter + '" />';
          });
        }
      }

    }

So I guess I run into a timing issue.

Here is how I try to get the Value of 'counter' - app.component.ts:

  import { Component, ViewChild, QueryList, ViewChildren } from '@angular/core';
  import { MyService } from './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 do I have to change, to get the correct Value after this.counter++; has reached its maximum value?

It is a job for RxJS :

Update your service :

export class MyService {
  counter: number = 0;
  ...
  counterSubject: BehaviorSubject<number> = new BehaviorSubject(this.counter);
  subscribeCounter = (s:any) => {
    this.counterSubject.asObservable().subscribe(s); //subscription to the next counter values
    this.counterSubject.next(this.counterSubject.getValue()); //get the current value at subscription
  }
  ...
  getSomeData() {
    //Do stuff to get some data from server, then call:
    cleanStrings();
    counterSubject.next(this.counter);
  }
  ...
}

Subscribe it in your 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
    });
  }
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM