【发布时间】:2016-07-15 04:47:03
【问题描述】:
我有一个指令 app.service.ts 存储应用程序状态数据,我正在尝试从其他组件中使用此指令,以便获取和设置应用程序的状态(正在运行)。
但是,当我尝试将此指令中的属性绑定到视图时,它给了我这个错误
EXCEPTION: Expression 'loading: {{loadState}} in App@0:23' has changed after it was checked. Previous value: 'false'. Current value: 'true' in [loading: {{loadState}} in App@0:23]
这里我试图显示加载文本,当appState.get().loadState == true
app.service.ts - source
import {Injectable} from 'angular2/core';
import {WebpackState} from 'angular2-hmr';
@Injectable()
export class AppState {
_state = {}; // you must set the initial value
constructor(webpackState: WebpackState) {
this._state = webpackState.select('AppState', () => this._state);
}
get(prop?: any) {
return this._state[prop] || this._state;
}
set(prop: string, value: any) {
return this._state[prop] = value;
}
}
app.ts
import {AppState} from './app.service';
export class App{
constructor(public appState: AppState) {
this.appState.set('loadState', false);
}
get loadState() {
return this.appState.get().loadState;
}
}
app.html
<div class="app-inner">
<p>loading: {{loadState}}</p>
<header></header>
<main layout="column" layout-fill>
<router-outlet></router-outlet>
</main>
</div>
假设 app.ts 有一个子组件 home.ts 并加载到视图中
home.ts
export class HomeCmp {
page;
constructor(private wp: WPModels, private appState: AppState) {}
ngOnInit() {
var pageId = this.appState.get().config.home_id;
this.appState.set('loadState', true); // before http request
this.wp.fetch(WPEnpoint.Pages, pageId).subscribe(
res => {
this.page = res;
this.appState.set('loadState', false); // after http request
},
err => console.log(err)
);
}
}
【问题讨论】:
-
您可以为此使用共享对象。我认为 HTML 中的
{{loadState}}总是会以这种方式抛出错误。而是尝试绑定一些在服务中使用的共享变量。例如。 _state={} 是一个共享对象。为其设置一些属性,然后在 html 中您可以通过{{appState._state.someProperty}}访问它 -
@micronyks 同样的错误
标签: angular