这是我的代码:
@echo off
setlocal EnableDelayedExpansion
for /f "usebackq tokens=1,9,10,11,12 delims= " %%a in ("all.txt") do (
if "%%b"=="count:" if "%%d"=="inuse:" (
set "feature=%%a"
set "count=%%c"
set "inuse=%%e"
echo count: !count!
echo inuse: !inuse!
echo feature: !feature!
echo.
)
)
pause
因为@Component({
selector: "foo",
template: `
<span>Init : {{o.init}}</span>
<span>Loaded data : {{o.loadedData}}</span>
`,
providers: [
Services
]
})
export class FooComponent implements OnInit{
constructor (private _services: Services) {}
o: Object
ngOnInit() {
o = {"init": "foo"}
this.services.randomCall()
.subscribe(
res => this.o["loadedData"] = res["loadedData"]
)
}
}
和模板渲染之间的竞争条件,o.loadedData
每次都不会出现。我希望在分配randomCall()
后通知角度。在angular1中,我会调用范围的o["loadedData"] = res["loadedData"]
函数。
我怎样才能在angular2中做类似的事情?
谢谢!
编辑:我加回了这个,这是一个错字。
答案 0 :(得分:4)
我会使用this
关键字:
o: Object
ngOnInit() {
this.o = {"init": "foo"}; // <-----
this.services.randomCall()
.subscribe(
res => {
this.o["loadedData"] = res["loadedData"]; // <-----
}
);
}
修改强>
您可以强制Angular2使用ChangeDetectorRef类检测更改,这样:
constructor(private cdr:ChangeDetectorRef) {
}
o: Object
ngOnInit() {
this.o = {"init": "foo"};
this.services.randomCall()
.subscribe(
res => {
this.o["loadedData"] = res["loadedData"];
this.cdr.detectChanges(); // <-----
}
);
}
答案 1 :(得分:1)
通常这是通过Angulars更改检测来完成的,该检测由其区域通知应该发生更改检测。当以某种方式在Angulars区域外运行的代码修改您的模型时,您可以手动调用更改检测,如
export class FooComponent implements OnInit{
constructor (private _services: Services, private cdRef:ChangeDetectorRef) {}
o: Object
ngOnInit() {
o = {"init": "foo"}
this.services.randomCall()
.subscribe(
res => {
o["loadedData"] = res["loadedData"];
this.cdRef.detectChanges();
});
)
}
}
由于Thierry提到的this
缺失,无论如何,手动更改检测都无法帮助您。
有关如何调用更改检测的更多选项,请参阅Triggering Angular2 change detection manually