我无法使用组件的某些属性动态更改 HTML 元素的状态。
@Component({
selector: 'home-page',
templateUrl: 'home.component.html',
styleUrls:['home.component.scss'],
providers:[AuthService]
})
export class HomeComponent implements OnInit {
public isAuth: boolean;
constructor(private auth: AuthService) {
ngOnInit() {
this.isAuth = this.auth.temp;
console.log(this.isAuth);
}
}
我的 AuthService 在这里:
@Injectable()
export class AuthService {
public activeUser:ReplaySubject<any> = new ReplaySubject();
dataBoolean$ = this.activeUser.asObservable();
set signIn(val: boolean) {
console.log("sign-in");
Observable.of(val).subscribe
(
res => {
this.activeUser.next(res);
console.log("SIGNIN >>>>> ", res);
this.temp = res;
}
);
console.log("temp", this.temp);
}
}
好的,当我单击按钮 signIn() 时,代码可以正常工作:我看到控制台的服务输出,然后是组件输出。
但是在我的模板中我有这个:
<button [disabled]="isAuth">Pull</button>
我认为当 Observable 发出新值时,我会在组件中得到它,并且组件的新属性应该立即显示在模板中。
即使这样:
setInterval(() => {
this.isAuth = !this.isAuth;
console.log(this.isAuth);
}, 2000);
按钮无法更改其状态。
但这不是真的,或者我做错了什么。
最佳答案
Angular 2 更改检测器使用区域
来检测更改。例如,如果你想使用计时器(如setInterval
),你必须这样做:
setInterval(() => {
this.isAuth = !this.isAuth;
console.log(this.isAuth);
this.cd.detectChanges();
}, 2000);
什么是 this.cd
属性?它是一个注入(inject)的 ChangeDetectorRef
:
constructor(private cd : ChangeDetectorRef) {}
但是为什么你必须这样做呢?因为在 Angular 2 中,变更检测器负责告诉 Ng2 何时更新 View 。
在那里您可以阅读很多相关内容:
http://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html
关于 Angular 2 : how to correctly change the template's variable via service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980043/