【发布时间】:2017-04-14 23:00:12
【问题描述】:
在 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++ 之后我需要改变什么,才能得到正确的值;已经达到最大值了吗?
【问题讨论】:
-
不要直接从服务中吃价值;而是创建一个动态更新的绑定。
-
你有例子吗?你会改进你的答案吗?我不明白。你的意思是为此实现setter和getter吗?谢谢!
标签: javascript angular angular-services