Angular2 서비스에서 replace 함수 내의 변수 값을 올립니다.타이밍 문제 : angle2 서비스에서 변수의 올바른 값을 얻는 방법은 무엇입니까?
다른 구성 요소의 값에 액세스 할 수 있지만 항상 시작 값을 얻습니다.
그래서 저는 항상 0을 얻습니다. 서비스의 생성자에서이를 변경하면 다른 값을 얻을 수 있지만, 필요한 것은 아닙니다.
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 + '" />';
});
}
}
}
그래서 내가 타이밍 문제로 실행 같아요
여기 내 service.ts입니다. 여기
내가 '카운터'의 가치 가려고하는 방법입니다 - app.component.ts : 나는 this.counter ++ 후 정확한 값을 얻기 위해 변경해야 할 무엇
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
}
을; 최대 값에 도달 했습니까?
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);
}
...
}
구성 요소에 가입 : 서비스가
업데이트 :
직접 서비스에서 값을 먹지 마십시오 대신에 즉시 업데이트 할 바인딩을 만듭니다. –
예제가 있습니까? 당신의 대답을 향상 시키시겠습니까? 나는 그것을 얻지 않는다. 이것을 위해 setter와 getter를 구현하려고 했습니까? 고맙습니다! –