2017-04-14 67 views
0

在Angular2服务中,我提高了替换函数中变量的值。时间问题:我如何从angular2服务获得正确的变量值

我能够访问另一个组件的值,但我总是得到起始值。所以我总是得到 - > 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 + '" />'; 
      }); 
     } 
     } 

    } 

所以我想我遇到一个时间问题。

这是我如何想方设法把“反”的值 - 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 ++,以获得正确的价值;已达到其最大值?

+0

不要吃直接从服务的价值;创建一个绑定来实时更新。 –

+0

你有一个例子吗?你能否改善你的答案?我不明白。你是否意味着为此实现setter和getter?谢谢! –

回答

1

这是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 
    }); 
    } 
    ... 
} 
+0

非常感谢! Works perfekt :-) –