我有一个简单的angular2(rc1)组件,它订阅了一个服务。当服务更新订阅时,我可以将结果记录在组件的订阅中,但视图不会更新。
我最初的怀疑是我的内部this
没有绑定到外部subscribe
,但是我在let self = this
回调上使用了一个胖箭头,并且还尝试了旧的self.SuccessMessage = result
在构造函数的第一行然后执行import {Component} from 'angular2/core';
import {Subscription} from 'rxjs/Subscription';
import {UploaderService} from './uploader.service';
@Component({
selector: 'aoma-uploader-status-mini',
providers: [],
viewProviders: [],
templateUrl: './app/uploader/mini-uploader-status.component.html'
})
export class MiniUploadStatusComponent {
subscription:Subscription;
successMessage:any = {};
constructor(private _uploaderService: UploaderService) {
// view correctly shows this value:
this.successMessage.serverMessage = 'before ';
this.subscription = _uploaderService.fileSuccess$.subscribe(result => {
// this fires and logs the result correctly:
console.log('the mini uploader: type of result', result);
// view is never updated here
this.successMessage = result;
})
}
}
无效。
我是否必须以某种方式强制进行更改检测?这是我的组成部分:
{{ successMessage | json }}
目前我的观点中只有class Parent {
let parentProperty = 1
}
class Child : Parent {
let childProperty = 2
}
class Test {
func testMethod<T : Parent>(data: T) {
// (llbd) print data
}
}
let child = Child()
let test = Test()
// (lldb) print child
test.testMethod(child)
。它再次正确显示'before'值,但在订阅获取结果对象时不会更改。
答案 0 :(得分:3)
看起来_uploaderService
在Angulars区域外运行。当值从其区域外部更改时,Angular不会检测到更改。
要使代码在区域内运行,请使用
constructor(private _uploaderService: UploaderService, private zone:NgZone) {
// view correctly shows this value:
this.successMessage.serverMessage = 'before ';
this.subscription = _uploaderService.fileSuccess$.subscribe(result => {
// this fires and logs the result correctly:
console.log('the mini uploader: type of result', result);
// view is never updated here
this.zone.run(() => this.successMessage = result);
})
}
还有其他方法可以通知Angular有关更改Manual Change Detection in AngularJS or Angular 2?
如果有额外的代码运行,例如在区域外调用router.navigate()
时,只有zone.run(...)
才能正确解决问题 - 除非有办法让您的服务在Angulars区域内运行第一名。