簡體   English   中英

時間問題:如何從angular2服務中獲取變量的正確值

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

在Angular2服務中,我在replace函數中提高了變量的值。

我可以從另一個組件訪問該值,但是我總是得到初始值。

因此,我總是得到->0。如果在服務的構造函數中更改它,則可以得到另一個值,但這不是我所需要的。

這是我的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 + '" />';
          });
        }
      }

    }

所以我想我遇到了時間問題。

這是我嘗試獲取'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
  }

我必須更改什么,才能在this.counter ++之后獲得正確的值; 已經達到最大值?

這是RxJS的工作:

更新您的服務:

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);
  }
  ...
}

將其訂閱到您的組件中:

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
    });
  }
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM