并不是我不想更新 View ,我只是不明白为什么当我期望它不更新时它会更新它(因为对象是在 NG 之外更新的)。
好的。
我有这个简单的代码:
@Component({
selector: 'my-app',
template: `
<div>
<input type='button' value="Fill more" (click)="fillMore()"/>
<ul>
<li *ngFor="let item of Items ">
{{item}}
</li>
</ul>
</div>
`,
})
export class App {
Items:Array<number> = new Array<number>();
constructor(private mySignalRService:MySignalRService)
{
this.Items.push(...[1,2,3]); //initial values
}
fillMore()
{
this.mySignalRService.go(this.Items);
}
}
正如你所看到的,我还注入(inject)了一项服务:
@Injectable()
export class MySignalRService
{
makeDummyDb:Promise<Array<number>>()
{
return new Promise( (v,x)=> {
setTimeout(function (){v([100,200,300]);},800);
})
}
go(arr : Array<number>) : number
{
this.makeDummyDb().then((newValues)=>arr.push(...newValues)) ;
return 5; //this method must return a number
}
}
现在 - 当我点击按钮(“填充更多”按钮)时,我确实看到了附加项目,但当我想到它时,它不是不应该更新,因为我相信 makeDummyDb:Promise 位于 Angular 的区域之外(我在这里可能是错的)
问题:
数组更新不是发生在 Angular 区域之外吗?如何模拟真实的外部区域以使代码不起作用? (用于测试)
最佳答案
如果您认为 setTimeout 或 Promise 将位于该区域“外部”,那么它就不是这样工作的; Angular 2 劫持了 setTimeout 和 setInterval (据我所知,当使用 TypeScript 时,querySelector 返回的是 IE Element 而不是 HTMLElement,强制强制转换来访问“style”之类的东西,尽管这并不与区域有任何关系,只是指出在 TS/Angular2 中,有些事情可能会做一些不同的事情)。每次超时结束时,都会发生更改检测。据我所知,这就是为什么你的值(value)被设定,对我来说一切都在该区域内。你必须采取一些明确的措施来避免这种情况。
解决这个问题的小例子:
ngZone.runOutsideAngular(() =>
Observable.interval(2500).subscribe(() => {
// async operation
});
关于javascript - Angular 2 在不应该更新 View 的时候更新了 View?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43448898/