Angular 2 : how to correctly change the template's variable via service?

标签 angular typescript service

我无法使用组件的某些属性动态更改 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/

相关文章:

angular - <ngx-qrcode> 不是 ionic 4 中的已知元素

angular - 使用 Angular 从 URL 中提取 id(2+ 直到最新)

Angular 键值管道排序属性/按顺序迭代

javascript - 在 typescript 中使用任何 Prop 定义对象

javascript - Angular 2,textarea(用文字附加表情符号)

typescript - 两个对象属性的交集

typescript - 使用 TypeScript 显式输入对象

amazon-s3 - 如何通过 Zend_Service_Amazon_S3 访问 Amazon s3 私有(private)存储桶对象

java - 启动动画服务 Activity

java - 创建 java C :\Program Files\Java\jdk1. 7.0_05\jre\bin\client\jvm.dll 失败